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.
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)