2

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?

corvid
  • 10,733
  • 11
  • 61
  • 130

3 Answers3

6

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]}
DaoWen
  • 32,589
  • 6
  • 74
  • 101
0

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.

Lochemage
  • 3,974
  • 11
  • 11
0

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] }
nwalsh
  • 471
  • 2
  • 9