Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate values between two dicts in Python

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

like image 331
Greg Brown Avatar asked Aug 31 '26 11:08

Greg Brown


2 Answers

You can use sum over a generator expression like this:

sum(float(v)*float(prices[k]) for k,v in data.iteritems())

like image 73
wim Avatar answered Sep 03 '26 02:09

wim


>>> 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
like image 24
Ashwini Chaudhary Avatar answered Sep 03 '26 00:09

Ashwini Chaudhary



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!