使用相同的键将两个词典组合成一个词典? [英] Combining two dictionaries into one with the same keys?
问题描述
我在这里浏览了一些问题,但这些问题似乎都不是我的问题.假设我有2个字典,它们是dict1
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}
和字典2
{'A':21, 'B': 12, 'C':62}
我正在编写一个程序,需要将它们组合成一个字典finaldict
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
推荐答案
这是通用版本.即使键中只有键,它也可以用来创建一个以值作为列表的字典.
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.viewkeys() | dic2.keys()):
if key in dic1: result.setdefault(key, []).append(dic1[key])
if key in dic2: result.setdefault(key, []).append(dic2[key])
print result
输出
{'A': [25, 21], 'C': [32, 62], 'B': [41, 12]}
如果您使用的是Python 3,则必须像这样更改for循环.感谢Martijn:)
If you are using Python 3, for loop has to be changed like this. Thanks to Martijn :)
for key in (dic1.keys() | dic2.keys()):
这篇关于使用相同的键将两个词典组合成一个词典?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!