簡體   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