问题
I have two collection.Counter()s, both of which of the same keys, so they look something like this:
01: 3
02: 2
03: 4
01: 8
02: 10
03: 13
I want the final result to look a bit more like this:
01: [3, 8]
02: [2, 10]
03: [4, 13]
How would I go about merging them?
回答1:
You can use a dict comprehension:
dict1 = {1: 3, 2: 2, 3: 4 }
dict2 = {1: 8, 2: 10, 3: 13 }
dict3 = { k: [ dict1[k], dict2[k] ] for k in dict1 }
# Result:
# dict3 = {1: [3, 8], 2: [2, 10], 3: [4, 13]}
回答2:
There aren't any automatic ways of doing this, you would have to manually loop through the arrays and combine them to a final output array yourself.
回答3:
You might run into some problems if one dictionary does not have the same key. It will throw a KeyField Error, otherwise this will work.
d1 = {01 : 3, 02: 2, 03: 4}
d2 = {01: 8, 02: 10, 03: 13}
d3 = {}
for key in d1.keys():
d3[key] = [d1[key], d2[key]]
and d3 will contain
{ 1 : [3, 8], 2: [2, 10], 3: [4, 13] }
来源:https://stackoverflow.com/questions/17732332/consolidating-two-dictionaries-with-the-same-keys-and-different-values