Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Divide the values of two dictionaries in python

I have two dictionaries with the same keys and I would like to do division on the values to update or create a new dictionary, keeping the keys intact, with the quotient as the new value for each of the keys.

d1 = { 'a':12 , 'b':10 , 'c':2 }
d2 = { 'a':0 , 'c':2 , 'b':5}
d3 = d2 / d1

d3 = { 'a':0 , 'b':0.5 , 'c':1 }

Aside from iterating through the key, value pairs and creating ordered lists of the values, then dividing, I'm not sure how to do this. I was hoping for a more elegant solution.

like image 887
ktflghm Avatar asked Aug 07 '12 06:08

ktflghm


People also ask

Can you divide dictionaries in Python?

Python division operation on DictPython division operation can be performed on the elements present in the dictionary using Counter() function along with '//' operator.

How do you divide a dictionary into values?

To divide each value in a dictionary by a number:Use a dict comprehension to iterate over the dictionary's items. On each iteration, divide the current value by the number and return the result.

How do you split a key in Python?

To do that you separate the key-value pairs by a colon(“:”). The keys would need to be of an immutable type, i.e., data-types for which the keys cannot be changed at runtime such as int, string, tuple, etc. The values can be of any type.

What does .values do in Python?

The values() method returns a view object. The view object contains the values of the dictionary, as a list.


2 Answers

Using viewkeys (python2.7):

{k: float(d2[k])/d1[k] for k in d1.viewkeys() & d2}

Same in python 3 (where we can drop the float() call altogether):

{k: d2[k]/d1[k] for k in d1.keys() & d2}

Yes, I am using a key intersection here; if you are absolutely sure your keys are the same in both, just use d2:

{k: float(d2[k])/d1[k] for k in d2}

And to be complete, In Python 2.6 and before you'll have to use a dict() constructor with a generator expression to achieve the same:

dict((k, float(d2[k])/d1[k]) for k in d2)

which generates a sequence of key-value tuples.

like image 100
Martijn Pieters Avatar answered Nov 06 '22 12:11

Martijn Pieters


This works for all pythons, I would however recommend the solution by @MartijnPieters if have Py 2.7+

>>> d1 = { 'a':12 , 'b':10 , 'c':2 }
>>> d2 = { 'a':0 , 'c':2 , 'b':5}
>>> d3 = dict((k, float(d2[k]) / d1[k]) for k in d2)
>>> d3
{'a': 0.0, 'c': 1.0, 'b': 0.5}
like image 43
jamylak Avatar answered Nov 06 '22 12:11

jamylak