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
251 views
in Technique[技术] by (71.8m points)

python - Combining two dictionaries into one with the same keys?

I've looked through a few of the questions here and none of them seem to be exactly my problem. Say I have 2 dictionaries, and they are dict1

{'A': 25 , 'B': 41, 'C': 32}

and dict 2

{'A':21, 'B': 12, 'C':62}

I'm writing a program where I need to combine these to one dictionary finaldict

{'A': [25 , 21], 'B': [41, 12], 'C': [32, 62]}

Any help is much appreciated, I've been working on this and getting nowhere for a while now

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

This is a generic version. This can be used to create a dictionary with values as a list, even if the key is present in only one of them.

dic1 = {'A': 25, 'B': 41, 'C': 32}
dic2 = {'A': 21, 'B': 12, 'C': 62}
result = {}
for key in (dic1.keys() | dic2.keys()):
    if key in dic1: result.setdefault(key, []).append(dic1[key])
    if key in dic2: result.setdefault(key, []).append(dic2[key])

print(result)

Output

{'A': [25, 21], 'C': [32, 62], 'B': [41, 12]}

If you are using Python 2, for loop has to be changed like this:

for key in (dic1.viewkeys() | dic2.keys()):

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

...