Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
897 views
in Technique[技术] by (71.8m points)

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

and

[
    {'device':'1','name':'x'},
    {'device':'2','name':'y'},
    {'device':'3','name':'z'}
]

How can I append each dictionary from the second list to the first list so as to get an output as:

[
    {'device':'1','name':'x','index': '1', 'color': 'red'},
    {'device':'1','name':'x','index': '2', 'color': 'blue'},
    {'device':'1','name': 'x','index': '3', 'color': 'green'}
    {'device':'2','name':'y''index': '1', 'color': 'red'},
    {'device':'2','name':'y','index': '2', 'color': 'blue'},
    {'device':'2','name':'y','index': '3', 'color': 'green'}
    {'device':'3','name':'z','index': '1', 'color': 'red'}, 
    {'device':'3','name':'z','index': '2', 'color': 'blue'}, 
    {'device':'3','name':'z','index': '3', 'color': 'green'}
]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...