将字典值除以另一个字典python的值

时间:2014-04-18 04:57:04

标签: python dictionary division

我有一个字典dict1,格式如下:

{0: 301, 1: 410, 2: 289}

我有另一本字典,dict2:

{0: 5307, 2: 4925}

我想根据键将dict2的值除以dict1的值。例如5307将被除以301,因为它们的键都是0.任何建议?

3 个答案:

答案 0 :(得分:3)

>>> d1 = {0: 301, 1: 410, 2: 289}
>>> d2 = {0: 5307, 2: 4925}
>>> {k: d2[k] / float(d1[k]) for k in d1 if k in d2}
{0: 17.631229235880397, 2: 17.041522491349482}

如果你的Python(例如2.6)对于字典理解来说太旧了,你可以使用

>>> dict((k, d2[k] / float(d1[k])) for k in d1 if k in d2)
{0: 17.631229235880397, 2: 17.041522491349482}

如果您的Python甚至超过2.6

>>> dict([(k, d2[k] / float(d1[k])) for k in d1 if k in d2])
{0: 17.631229235880397, 2: 17.041522491349482}

在Python3中,您不需要float调用

>>> {k: d2[k] / d1[k] for k in d1 if k in d2}
{0: 17.631229235880397, 2: 17.041522491349482}

答案 1 :(得分:1)

def divide(dividends, divisors):
    ret = dict()
    for key, dividend in dividends.iteritems():
        if key in divisor:
            ret[key] = dividend/divisors[key]
        else:
            ret[key] = dividend
    return ret

答案 2 :(得分:0)

在每个项目上循环最小字典的长度。然后将值添加到另一个词典values

>>> dict1 = {0: 301, 1: 410, 2: 289}
>>> 
>>> dict2 = {0: 5307, 1: 4925}
>>> 
>>> length = {len(dict1): 'dict1', len(dict2): 'dict2'}
>>> small = min(length)
>>> values = {}
>>> 
>>> for k in range(small):
...     values[k] = dict1[k]*dict2[k]
... 
>>> print values
{0: 1597407, 1: 2019250}
>>>