简体   繁体   中英

Append Python List of Dictionaries by loops

I have 2 Python List of Dictionaries:

[{'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': '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'}]

(Don't be confused by order of items in individual directories as directories are not ordered.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM