[英]Append Python List of Dictionaries by loops
I have 2 Python List of Dictionaries: 我有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'}]
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 think that the following code answers your question: 我认为以下代码可以回答您的问题:
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)
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)
The output: 输出:
[{'name': 'x', 'device': '1'}, {'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':'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':'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.) (不要对单个目录中的项目顺序感到困惑,因为目录没有顺序。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.