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.
Martijn pieters
source share