Reputation: 1483
How to create a function which calculates the total value from 2 given dictionary
Upvotes: 0
Views: 248
Reputation: 414875
>>> from collections import Counter
>>> d1 = dict(a=1, b=2)
>>> d2 = dict(a=2, b=1, c=3)
>>> c = Counter(**d1)
>>> c.update(**d2)
>>> c
Counter({'a': 3, 'c': 3, 'b': 3})
Upvotes: 0
Reputation: 64933
If you have your data in a something like this:
Part = collections.namedtuple('Part', 'key name price')
parts = {
'WH239': Part('WH239', 'Mountain Bike Wheel', 5000),
'TR202': Part('TR202', 'Mountain Bike Tire', 2000),
'TU277': Part('TU277', 'Mountain Bike Tube', 2000),
'FR201': Part('FR201', 'Mountain Bike Frame', 60000),
}
Product = collections.namedtuple('Product', 'key name parts')
product = Product(
'bike201',
'Mountain Bike',
[('WH239', 2), ('TR202', 2), ('TU277', 2), ('FR201', 1)]
)
then you can do something like this:
product_price = sum(n*parts[part_name].price for part_name, n in product.parts)
Upvotes: 2