0

I wanted to sum 2 dictonaries

inv = {'gold coin': 41, 'rope': 1}
inv2 = {'rope': 3, 'torch': 10}

I achieved it with Counter subclass

inv = Counter({'gold coin': 41, 'rope': 1})
inv2 = Counter({'rope': 3, 'torch':10})
result = dict(inv + inv2)
print(result)

With output:

{'gold coin': 41, 'rope': 4, 'torch': 10}

And now i'm curious if it's possible to sum those 2 dictionaries with loop and other ways.

Any ideas ?

leronx
  • 31
  • 3
  • Also have a look at this as its achieved with many ways: https://stackoverflow.com/questions/11011756/is-there-any-pythonic-way-to-combine-two-dicts-adding-values-for-keys-that-appe – utengr Oct 27 '17 at 23:20

4 Answers4

2

You can try this:

import itertools
inv = {'gold coin': 41, 'rope': 1}
inv2 = {'rope': 3, 'torch': 10}
final_data = [(a, list(b)) for a, b in itertools.groupby(list(inv.items())+list(inv2.items()), key=lambda x:x[0])]
new_final_data = {a:sum(c for i, c in b) for a, b in final_data}

Output:

{'gold coin': 41, 'rope': 4, 'torch': 10}
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
2

You can use a dict comprehension -

print({k: inv.get(k, 0) + inv2.get(k, 0) for k in set(inv) | set(inv2) })

prints - {'gold coin': 41, 'rope': 4, 'torch': 10}

0TTT0
  • 1,288
  • 1
  • 13
  • 23
Manish Giri
  • 3,562
  • 8
  • 45
  • 81
2
inv = {'gold coin': 41, 'rope': 1}
inv2 = {'rope': 3, 'torch': 10}
result = {val: inv.get(val, 0) + inv2.get(val, 0) for val in set(inv).union(inv2)}
print(result)

output:

{'torch': 10, 'rope': 4, 'gold coin': 41}
utengr
  • 3,225
  • 3
  • 29
  • 68
1

Here's a longer way to do it with loops, so you can add as many dicts together as you want

inv = {'gold coin': 41, 'rope': 1,}
inv2 = {'rope': 3, 'torch': 10}

def sum_dicts(*args):
    new_dict ={}
    for arg in args:
        for key, value in arg.items():
            if key in new_dict:
                new_dict[key] += value
            else: 
                new_dict[key] = value
    return new_dict

print(sum_dicts(inv, inv2))
0TTT0
  • 1,288
  • 1
  • 13
  • 23