Separate the values ​​of two dictionaries in python

I have two dictionaries with the same keys, and I would like to divide by values ​​to update or create a new dictionary, keeping the keys unchanged, and the private one as a 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 } 

Besides iterating over a key, pairing values, and creating ordered lists of values ​​and then dividing, I'm not sure how to do this. I was hoping for a more elegant solution.

+8
python dictionary division
source share
4 answers

Using viewkeys (python2.7):

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

The same thing in python 3 (where we can refuse the call to float() altogether):

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

Yes, here I use a key junction; if you are absolutely sure that 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 need to use the 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 tuples with a key.

+13
source share

This works for all pythons, however I would recommend @MartijnPieters solution if 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} 
+5
source share
 d1 = { 'a':12 , 'b':10 , 'c':2 } d2 = { 'a':0 , 'c':2 , 'b':5} d3={x:float(d2[x])/d1[x] for x in d1} print d3 

exit:

 {'a': 0.0, 'c': 1.0, 'b': 0.5} 
+4
source share

in 3.2 you use the .keys () method and the .get () key. http://www.tutorialspoint.com/python/python_dictionary.htm

+1
source share

All Articles