Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Merge and sum of two dictionaries

I have a dictionary below, and I want to add to another dictionary with not necessarily distinct elements and merge it's results. Is there any built-in function for this, or will I need to make my own?

{   '6d6e7bf221ae24e07ab90bba4452267b05db7824cd3fd1ea94b2c9a8': 6,   '7c4a462a6ed4a3070b6d78d97c90ac230330603d24a58cafa79caf42': 7,   '9c37bdc9f4750dd7ee2b558d6c06400c921f4d74aabd02ed5b4ddb38': 9,   'd3abb28d5776aef6b728920b5d7ff86fa3a71521a06538d2ad59375a': 15,   '2ca9e1f9cbcd76a5ce1772f9b59995fd32cbcffa8a3b01b5c9c8afc2': 11 } 

The number of elements in the dictionary is also unknown.

Where the merge considers two identical keys, the values of these keys should be summed instead of overwritten.

like image 571
badc0re Avatar asked May 05 '12 11:05

badc0re


People also ask

Can you merge two dictionaries?

You can merge two dictionaries by iterating over the key-value pairs of the second dictionary with the first one.

How do I merge two dictionaries in a single expression?

Using | in Python 3.9 In the latest update of python now we can use “|” operator to merge two dictionaries. It is a very convenient method to merge dictionaries.


2 Answers

You didn't say how exactly you want to merge, so take your pick:

x = {'both1': 1, 'both2': 2, 'only_x': 100} y = {'both1': 10, 'both2': 20, 'only_y': 200}  print {k: x.get(k, 0) + y.get(k, 0) for k in set(x)} print {k: x.get(k, 0) + y.get(k, 0) for k in set(x) & set(y)} print {k: x.get(k, 0) + y.get(k, 0) for k in set(x) | set(y)} 

Results:

{'both2': 22, 'only_x': 100, 'both1': 11} {'both2': 22, 'both1': 11} {'only_y': 200, 'both2': 22, 'both1': 11, 'only_x': 100} 
like image 97
georg Avatar answered Oct 12 '22 01:10

georg


You can perform +, -, &, and | (intersection and union) with collections.Counter().

We can do the following (Note: only positive count values will remain in the dictionary):

from collections import Counter  x = {'both1':1, 'both2':2, 'only_x': 100 } y = {'both1':10, 'both2': 20, 'only_y':200 }  z = dict(Counter(x)+Counter(y))  print(z) [out]: {'both2': 22, 'only_x': 100, 'both1': 11, 'only_y': 200} 

To address adding values where the result may be zero or negative, use Counter.update() for addition, and Counter.subtract() for subtraction:

x = {'both1':0, 'both2':2, 'only_x': 100 } y = {'both1':0, 'both2': -20, 'only_y':200 } xx = Counter(x) yy = Counter(y) xx.update(yy) dict(xx) [out]: {'both2': -18, 'only_x': 100, 'both1': 0, 'only_y': 200} 
like image 35
Scott Avatar answered Oct 12 '22 02:10

Scott