Python List Of Dictionaries By Loops
Solution 1:
If you want only print the resulting dictionaries, uncomment the print statement (and comment the following 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)
The result:
[{'name': 'x', 'device': '1', 'color': 'red', 'index': '1'}, {'name': 'y', 'device': '2', 'color': 'red', 'index': '1'}, {'name': 'z', 'device': '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': '1', 'color': 'green', 'index': '3'}, {'name': 'y', 'device': '2', 'color': 'green', 'index': '3'}, {'name': 'z', 'device': '3', 'color': 'green', 'index': '3'}]
Solution 2:
If you just want to merge the n.-th dict of the first list with the n.-th dict of the second list you can do something like this:
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'}
]
defmerge(x,y):
z = x.copy()
z.update(y)
return z
>>> [merge(x,y) for x,y inzip(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)
is a helper function that returns a single dictionary with all contents of x and y.
zip(a,b)
returns a list of tuples, where the first element of each tuple is an element of a and the second element is an element of b. This allows to use list comprehensions on two lists in parallel.
Post a Comment for "Python List Of Dictionaries By Loops"