【发布时间】:2017-12-04 12:23:12
【问题描述】:
我有 2 个 python 字典列表:
[
{'index':'1','color':'red'},
{'index':'2','color':'blue'},
{'index':'3','color':'green'}
]
和
[
{'device':'1','name':'x'},
{'device':'2','name':'y'},
{'device':'3','name':'z'}
]
如何将第二个列表中的每个字典附加到第一个列表中,以便获得如下输出:
[
{'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'}
]
【问题讨论】:
-
device键在结果列表中的第 2 和第 3 个字典上去了哪里? -
为什么输入总共有6个字典,输出有9个?一些字典看起来已合并,但设备密钥仅在输出字典之一中?
-
为什么输出是“列表列表”?
-
在您的示例输出中,第一个列表的第一个字典是您想要的更新字典。但是,其他所有字典都只添加了“颜色”作为键。这是为什么?他们不应该都有“设备”作为键吗?
-
是的,这是错误发生的,我更新了它。
标签: python list dictionary