按循环追加Python字典列表

按循环追加Python字典列表,python,list,dictionary,Python,List,Dictionary,我有两个Python字典列表: [{'index':'1','color':'red'},{'index':'2','color':'blue'},{'index':'3','color':'green'}] & 如何将第二个列表中的每个字典附加到第一个列表中,以获得如下输出: [{'device':'1','name':'x'},{'index':'1','color':'red'},{'index':'2','color':'blue'},{'index':'3','color':'

我有两个Python字典列表:

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

如何将第二个列表中的每个字典附加到第一个列表中,以获得如下输出:

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

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

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


(不要被单个目录中项目的顺序所迷惑,因为目录没有顺序。)

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

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)

你可能想考虑是否有一个更好的结构来实现你想要达到的目的——这些多级嵌套列表和字典可能会很难处理。当然,我会研究一下。谢谢你。[{'name':'x','device':'1,'index':'1','color':'red'},{'name':'x','index':'2','color':'blue'},{'name':'x','index':'3','color':'green'}][{'name':'y','index':'1','color':'red red},{'name':'y','y','index':'2','color':'blue','blue',{'name':'y','y','index':'3','color':'green':'green':'z':',{'name':'z','index':'2','color':'blue'},{'name':'z','index':'3','color':'green'}]这可能吗?在Python中,一切都是可能的。请将其表述为一个新问题,我会回答你。(然后请在这里写下你对新问题的评论,以便我得到通知。)我把它表述为一个新的问题,上面有我给出的链接。我已经回答了它-我首先要请求取消它。
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)