Multiplying values from two different dictionaries together in Python

老子叫甜甜 提交于 2020-01-10 04:01:05

问题


I have two separate dictionaries with keys and values that I would like to multiply together. The values should be multiplied just by the keys that they have.

i.e.

dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'a': 15, 'b': 10, 'd': 17}

dict3 = dict.items() * dict.items()
print dict3

#### #dict3 should equal 
{'a': 15, 'b': 20}

If anyone could help, that would be great. Thanks!


回答1:


You can use a dict comprehension:

>>> {k : v * dict2[k] for k, v in dict1.items() if k in dict2}
{'a': 15, 'b': 20}

Or, in pre-2.7 Python, the dict constructor in combination with a generator expression:

>>> dict((k, v * dict2[k]) for k, v in dict1.items() if k in dict2)
{'a': 15, 'b': 20}



回答2:


From my telephone, so bit hard to type code. This should do the trick:

for key, value in dict1.iteritems():
    if key in dict2:
         dict3[key] = int(dict1[key]) * int(dict2[key])



回答3:


dict1 = {'a': 1, 'b': 2, 'c': 3}
dict2 = {'a': 15, 'b': 10, 'd': 17}

def dict_mul(d1, d2):
    d3 = dict()
    for k in d1:
        if k in d2:
            d3[k] = d1[k] * d2[k]
    return d3

print dict_mul(dict1, dict2)


来源:https://stackoverflow.com/questions/15334783/multiplying-values-from-two-different-dictionaries-together-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!