0

I have the following three dictionaries:

d1 = {'python':15, 'java':2,'c#':3}
d2 = {'go':30,'c#':4, 'java':10,}
d3 = {'python':2,'ruby':7}

I have used the following code to merge and sum all values of the same keys.

d={}
for mydict in d1,d2,d3:
    for key in mydict:
        d[key] = d.get(key,0) + mydict[key]
print(d)

But I am not able to change this code into a comprehension.

I have already done it using collection.Counter and Itertools.chain() method.

John
  • 740
  • 5
  • 13
  • 36

3 Answers3

0

Try this:

d = {}
d = {key: di[key] + d.get(key, 0) for di in (d1, d2, d3) for key in di}

Output:

{'python': 2, 'java': 10, 'c#': 4, 'go': 30, 'ruby': 7}

What we do is iterate over each key in each dict and add the corresponding key, value pair.

snatchysquid
  • 1,283
  • 9
  • 24
0

One way using collections.Counter:

from collections import Counter

sum([Counter(d) for d in [d1, d2, d3]], Counter())

Output:

Counter({'python': 17, 'java': 12, 'c#': 7, 'go': 30, 'ruby': 7})
Chris
  • 29,127
  • 3
  • 28
  • 51
  • yes I have already tried it using Counter and Chain method. But couldn't convert it to comprehension – John Sep 12 '20 at 10:19
0

I am aware that the solution is not based on comprehension but I think it is more clear and direct.

from typing import List
from collections import defaultdict

def merge_dicts(dicts: List[dict]):
    result = defaultdict(int)
    for d in dicts:
        for k,v in d.items():
            result[k] += v
    return result


d1 = {'python':15, 'java':2,'c#':3}
d2 = {'go':30,'c#':4, 'java':10,}
d3 = {'python':2,'ruby':7}

final_dict = merge_dicts([d1,d2,d3])
print(final_dict)

output

defaultdict(<class 'int'>, {'python': 17, 'java': 12, 'c#': 7, 'go': 30, 'ruby': 7})
balderman
  • 22,927
  • 7
  • 34
  • 52