Pregunta

I have a dictionary, dict1, in the following format:

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

I have another dictionary, dict2:

{0: 5307, 2: 4925}

I would like to divide the value of dict2 by the value of dict1, based on the keys. For example 5307 would be divided by 301 since their keys are both 0. Any suggestions?

¿Fue útil?

Solución 2

def divide(dividends, divisors):
    ret = dict()
    for key, dividend in dividends.items():
        ret[key] = dividend/divisors.get(key, 1)
    return ret

Otros consejos

>>> 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}

If your Python (eg 2.6) is too old for dict comprehensions, you can use

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

If your Python is even older than 2.6

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

In Python3, you don't need the float call

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

Loop over every item the length of the smallest dict. Then add the values to another dict, 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}
>>> 
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top