Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiplying values from two different dictionaries together in Python

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!

like image 632
user2156072 Avatar asked Mar 11 '13 09:03

user2156072


1 Answers

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}
like image 102
Niklas B. Avatar answered Oct 06 '22 17:10

Niklas B.