[Solved] Python List of Dictionaries by Loops


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

0

solved Python List of Dictionaries by Loops