Divide the values of two dictionaries in python

后端 未结 4 1275
离开以前
离开以前 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}
    
    0 讨论(0)
  • 2020-12-16 03:14

    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.

    0 讨论(0)
  • 2020-12-16 03:21

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

    0 讨论(0)
  • 2020-12-16 03:24
    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
    

    output:

    {'a': 0.0, 'c': 1.0, 'b': 0.5}
    
    0 讨论(0)
提交回复
热议问题