Reputation: 15
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'}]
Upvotes: 1
Views: 173
Reputation: 221
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)
Upvotes: 2
Reputation: 14131
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.)
Upvotes: 0