我有2个Python词典列表:
import quopri
message = quopri.decodestring(payload).decode('utf-8')
print(message)
&安培;
[{'index':'1','color':'red'},{'index':'2','color':'blue'},{'index':'3','color':'green'}]
如何将第二个列表的每个字典附加到第一个列表,以便输出为:
[{'device':'1','name':'x'},{'device':'2','name':'y'},{'device':'3','name':'z'}]
答案 0 :(得分:2)
我认为以下代码可以回答您的问题:
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)
答案 1 :(得分:0)
我不知道你想保存结果列表的位置,所以我打印出来了:
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'}]
(不要因个别目录中的项目顺序而混淆,因为目录未被订购。)