通过循环附加Python字典列表 [英] Append Python List of Dictionaries by loops

查看:113
本文介绍了通过循环附加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 of second list to the first list so as to get an output as:

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

推荐答案

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

I don't know where you wanted to save your result lists, so I printed them out:

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

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

(不要被单个目录中项目的顺序所混淆,因为目录没有顺序.)

(Don't be confused by order of items in individual directories as directories are not ordered.)

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

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