2017-06-29 178 views
1

我有字典的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'},{'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'}] 
+0

您可能需要考慮,如果對於你想要達到的目標有一個更好的結構 - 這些多級嵌套列表和字典可能很難處理。 – Ramon

+0

當然,我會研究它。謝謝。 –

回答

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) 

輸出:

[{ '名稱': 'X', '裝置': '1'},{ '索引': '1',「顏色':'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'}]

(不要被各個目錄項目的順序被混淆,目錄不排序)

+0

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

+0

在Python中,一切皆有可能。請把它作爲一個新問題來形成,我會回答你。 (然後請在這裏寫下關於你的新問題**的評論,以便我會收到通知。) – MarianD

+0

https://stackoverflow.com/questions/44848193/python-list-of-dictionaries-by-loops –

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)