Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to subtract values from dictionaries

Tags:

I have two dictionaries in Python:

d1 = {'a': 10, 'b': 9, 'c': 8, 'd': 7} d2 = {'a': 1, 'b': 2, 'c': 3, 'e': 2} 

I want to substract values between dictionaries d1-d2 and get the result:

d3 = {'a': 9, 'b': 7, 'c': 5, 'd': 7 } 

Now I'm using two loops but this solution is not too fast

for x,i in enumerate(d2.keys()):         for y,j in enumerate(d1.keys()): 
like image 414
Colargol Avatar asked Jul 16 '13 08:07

Colargol


People also ask

How do you subtract a value from a dictionary in python?

Method #2 : Using Counter() + “-” operator In this, the Counter function converts the dictionary in the form in which the minus operator can perform the task of subtraction.

Can I subtract one dictionary from another Python?

With set. Here we take two dictionaries and apply set function to them. Then we subtract the two sets to get the difference. We do it both ways, by subtracting second dictionary from first and next subtracting first dictionary form second.


1 Answers

I think a very Pythonic way would be using dict comprehension:

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

Note that this only works in Python 2.7+ or 3.

like image 122
Erfa Avatar answered Nov 18 '22 19:11

Erfa