python combining dictionary results with overlapping keys

Viewed 85

I have a frequency distribution dictionary as a feature column in a pandas dataframe.

I want to join all the key value pairs from the dictionary for a given week and combine them such that sum of frequencies for the words that repeat in the week updates the key-value pair for the new dictionary.

Ex:

dict{'apple' : 3, 'banana' : 4}
dict{'apple' : 5, 'banana' : 7, 'orange' : 2}

# to become
dict{'apple' : 8, 'banana' : 11, 'orange' : 2}

Is there a way to do this that isn't manually creating a new dictionary and searching each one item by item?

3 Answers

A subclass of dict, Counter was made for use cases just like this:

from collections import Counter

d1 = {'apple' : 3, 'banana' : 4}
d2 = {'apple' : 5, 'banana' : 7, 'orange' : 2}
d3 = dict(Counter(d1) + Counter(d2))
print(d3)

Output:

{'apple': 8, 'banana': 11, 'orange': 2}

if you want to write a Script without any library, you can solve like this but you should give a value to your dictionaries:

a = {'apple' : 3, 'banana' : 4}
b = {'apple' : 5, 'banana' : 7, 'orange' : 2}
output = {}
for i in a:
 output[i]=output.get(i,0)+a[i]
for i in b:
 output[i]=output.get(i,0)+b[i]
print(output)

as you can see i using for loop and null dict for solving

If you can create d1 (or d2) using defaultdict, you can remove the need of a 3rd dictionary:

from collections import defaultdict
d1 = defaultdict(int, {'apple' : 3, 'banana' : 4})
d2 = {'apple' : 5, 'banana' : 7, 'orange' : 2}

for key, val in d2.items():
    d1[key] += val
print(d1)

# output
defaultdict(<class 'int'>, {'apple': 8, 'banana': 11, 'orange': 2})
Related