Divide the values of two dictionaries in python

后端 未结 4 1281
离开以前
离开以前 2020-12-16 02:34

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

4条回答
  •  死守一世寂寞
    2020-12-16 03:01

    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}
    

提交回复
热议问题