Reputation: 1299
I have two dict in python one of quantities and the other of prices the both have the same keys What is the best, and quicks way to calculate Quantity * price for each element in the dict
Example
prices = {'a': '40', 'b': '40', 'c': '35'}
data ={'a': '1', 'b': '2', 'c': '4'}
I want to get a total sum (int) of 260
Upvotes: 3
Views: 4480
Reputation: 251096
>>> prices = {'a': '40', 'b': '40', 'c': '35'}
>>> data ={'a': '1', 'b': '2', 'c': '4'}
>>> sum(int(prices[x])*int(data[x]) for x in data)
260
Upvotes: 1
Reputation: 363123
You can use sum
over a generator expression like this:
sum(float(v)*float(prices[k]) for k,v in data.iteritems())
Upvotes: 2