Multiplying values from two different dictionaries together in Python

我的未来我决定 提交于 2019-12-01 05:24:16

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}

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