Greg Brown
Greg Brown

Reputation: 1299

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

Upvotes: 3

Views: 4480

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

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

wim
wim

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

Related Questions