循环字典的Python列表 [英] Python List of Dictionaries by Loops

查看:111
本文介绍了循环字典的Python列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有2个python字典列表:

I have 2 python list of dictionaries:

[
    {'index':'1','color':'red'},
    {'index':'2','color':'blue'},
    {'index':'3','color':'green'}
]

[
    {'device':'1','name':'x'},
    {'device':'2','name':'y'},
    {'device':'3','name':'z'}
]

如何将每个字典从第二个列表追加到第一个列表,以得到如下输出:

How can I append each dictionary from the second list to the first list so as to get an output as:

[
    {'device':'1','name':'x','index': '1', 'color': 'red'},
    {'device':'1','name':'x','index': '2', 'color': 'blue'},
    {'device':'1','name': 'x','index': '3', 'color': 'green'}
    {'device':'2','name':'y''index': '1', 'color': 'red'},
    {'device':'2','name':'y','index': '2', 'color': 'blue'},
    {'device':'2','name':'y','index': '3', 'color': 'green'}
    {'device':'3','name':'z','index': '1', 'color': 'red'}, 
    {'device':'3','name':'z','index': '2', 'color': 'blue'}, 
    {'device':'3','name':'z','index': '3', 'color': 'green'}
]

推荐答案

如果只想打印结果字典,请取消注释打印语句(并注释以下2个注释).

If you want only print the resulting dictionaries, uncomment the print statement (and comment the following 2).

d1 = [
    {'index':'1','color':'red'},
    {'index':'2','color':'blue'},
    {'index':'3','color':'green'}
]

d2 = [
    {'device':'1','name':'x'},
    {'device':'2','name':'y'},
    {'device':'3','name':'z'}
]


result_list = []
for dict1 in d1:
    merged_dict = dict1.copy()
    for dict2 in d2:
        merged_dict.update(dict2)
#       print(merged_dict)
        result_list.append(merged_dict.copy())

print(result_list)

结果:

[{'name':'x','device':'1','color':'red','index':'1'},
{'name':'y','device':'2','color':'red','index':'1'},
{'name':'z','device':'3','color':'red','index':'1'},
{'name':'x','device':'1','color':'blue','index':'2'},
{'name':'y','device':'2','color':'blue','index':'2'},
{'name':'z','device':'3','color':'blue','index':'2'},
{'name':'x','device':'1','color':'green','index':'3'},
{'name':'y','device':'2','color':'green','index':'3'},
{'name':'z','device':'3','color':'green','index':'3'}]

[{'name': 'x', 'device': '1', 'color': 'red', 'index': '1'},
{'name': 'y', 'device': '2', 'color': 'red', 'index': '1'},
{'name': 'z', 'device': '3', 'color': 'red', 'index': '1'},
{'name': 'x', 'device': '1', 'color': 'blue', 'index': '2'},
{'name': 'y', 'device': '2', 'color': 'blue', 'index': '2'},
{'name': 'z', 'device': '3', 'color': 'blue', 'index': '2'},
{'name': 'x', 'device': '1', 'color': 'green', 'index': '3'},
{'name': 'y', 'device': '2', 'color': 'green', 'index': '3'},
{'name': 'z', 'device': '3', 'color': 'green', 'index': '3'}]

这篇关于循环字典的Python列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆