2017-06-30 104 views
-4

我的字典2 Python列表: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'}, 
    {'device':'1','name':'x','index': '2', 'color': 'blue'}, 
    {'device':'1','name': 'x','index': '3', 'color': 'green'} 
    {'device':'2','name':'y''index': '1', 'color': 'red'}, 
    {'device':'2','name':'y','index': '2', 'color': 'blue'}, 
    {'device':'2','name':'y','index': '3', 'color': 'green'} 
    {'device':'3','name':'z','index': '1', 'color': 'red'}, 
    {'device':'3','name':'z','index': '2', 'color': 'blue'}, 
    {'device':'3','name':'z','index': '3', 'color': 'green'} 
] 
+2

其中做'device'鍵在結果列表中的第二和第三個字符上? –

+0

爲什麼總共有6個詞典在輸入中,9個在輸出中?一些字典看起來合併了,但設備密鑰只在其中一個輸出字典中出現? – citizen2077

+2

爲什麼輸出是「列表清單」? –

回答

1

如果您只想打印生成的字典,請取消註釋打印語句(並註釋以下2)。

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


result_list = [] 
for dict1 in d1: 
    merged_dict = dict1.copy() 
    for dict2 in d2: 
     merged_dict.update(dict2) 
#  print(merged_dict) 
     result_list.append(merged_dict.copy()) 

print(result_list) 

其結果是:

[{ '名稱': 'X', '裝置': '1', '顏色': '紅', '索引': '1'}
{'name':'z','device':'2','color':'red','index':'1' ':'3','color':'red','index':'1'},
{'name':'x','device':'1','color':'blue', 'index':'2'},
{'name':'y','device':'2','color':'blue','index':'2'},
{'name':'z','device':'3','color':'blue','index':'2'},
{'name':'x','device': '','顏色':'綠色','索引':'3'},
{'name':'y','device':'2','color':'green','index ': '3'},
{' 名稱': 'Z', '裝置': '3', '顏色': '綠色', '索引': '3'}]

-1

如果您只想將第一個列表的第n個字典與第n個字典合併F中的第二個列表,你可以做這樣的事情:

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

b = [ 
    {'device':'1','name':'x'}, 
    {'device':'2','name':'y'}, 
    {'device':'3','name':'z'} 
] 

def merge(x,y): 
    z = x.copy() 
    z.update(y) 
    return z 

>>> [merge(x,y) for x,y in zip(a,b)] 

[{'color': 'red', 'device': '1', 'index': '1', 'name': 'x'}, 
{'color': 'blue', 'device': '2', 'index': '2', 'name': 'y'}, 
{'color': 'green', 'device': '3', 'index': '3', 'name': 'z'}] 

merge(x,y)是一個輔助函數,返回x和y的所有內容的單個字典。

zip(a,b)返回元組列表,其中每個元組的第一個元素是a的元素,第二個元素是b的元素。這允許並行使用兩個列表上的列表解析。

+0

你爲什麼要回答這個問題? OP在16小時前發佈了完全相同的問題(已回答)。回答明顯的欺騙只會鼓勵這種行爲。 – That1Guy

+0

實際上它不是一回事,輸出是不一樣的 –