繁体   English   中英

通过循环附加Python字典列表

[英]Append Python List of Dictionaries by loops

我有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'},{'index':'2','color':'blue'},{'index':'3','color':'green'}]

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

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

我认为以下代码可以回答您的问题:

indexes = [
    {'index':'1','color':'red'},
    {'index':'2','color':'blue'},
    {'index':'3','color':'green'}
]
devices = [
    {'device':'1','name':'x'},
    {'device':'2','name':'y'},
    {'device':'3','name':'z'}
]
new_lists = [[device] for device in devices]
for new_list in new_lists:
    new_list.extend(indexes)

我不知道您要将结果列表保存在哪里,所以我将它们打印出来:

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'}]

for item in d2:
    print ([item] + d1)

输出:

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

(不要对单个目录中的项目顺序感到困惑,因为目录没有顺序。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM