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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With