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
You can use sum over a generator expression like this:
sum(float(v)*float(prices[k]) for k,v in data.iteritems())
>>> 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
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