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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…