在Python中将来自两个不同词典的值相乘在一起 [英] Multiplying values from two different dictionaries together in Python

查看:134
本文介绍了在Python中将来自两个不同词典的值相乘在一起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个独立的词典,其中包含键和值,我想将它们叠加在一起。值应该乘以它们所拥有的键。



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

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

#####dict3应该等于
{'a':15,'b':20}

如果有人可以帮忙,那会很棒。
谢谢!

解决方案

您可以使用 dict comprehension

 >>>对于k中的k,v * dict2 [k],在dict1.items()中,如果k在dict2中} k 
{'a':15,'b':20}

或者,在2.7之前的Python中, dict 构造函数与生成器表达式

 >>>如果在dict2中的k,则在dict1.items()中的k,v的dict((k,v * dict2 [k]))
{'a':15,'b':20}


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!

解决方案

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}

这篇关于在Python中将来自两个不同词典的值相乘在一起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆