Fede Couti Fede Couti - 5 months ago 6x
Python Question

How to loop through two dictionaries in Python

I want to make a for loop that can go through two dictionaries, make a calculation and print the result. This is the code:

price = {
"banana": 4,
"apple": 2,
"orange": 1.5,
"pear": 3

inventory = {
"banana": 6,
"apple": 0,
"orange": 32,
"pear": 15

for k, v in price, inventory:
total = total + price*inventory
print total

I want to know how much money would I make if I sold every item in this "store". I have already checked here but it didn't work out for me.

The error message is this:

Traceback (most recent call last):
File "python", line 15, in <module>
ValueError: too many values to unpack

Line 15 is the one where the for loop starts.
I don't know if I'm thinking how to do it in the right way.


You can zip the dicts:

for k, k2 in zip(price,inventory):

even if your code worked you would be accessing the keys not the values so you would need to access the dict values using each key as above.

If you are using python2 you can use itertools.izip:

from itertools import izip
for k, k2 in izip(price,inventory):

Because dicts are unordered you need to use an orderedDict to make sure the keys matched up.

If the dicts both have the same keys a simpler solution would be use the keys from one dict to get the values from both.

for k in price:

which can be written as:

total = sum(price[k]*inventory[k]for k in price)

If you control how the dicts are created combining both into one dict storing a dict of dicts using price and inventory as keys would be a better overall solution.

shop_items = {'orange': {'price': 1.5, 'inventory': 32}, 'pear': {'price': 3, 'inventory': 15}, 'banana': {'price': 4, 'inventory': 6}, 'apple': {'price': 2, 'inventory': 0}}

Then to get the total:

print(sum(d["price"] * d["inventory"] for d in shop_items.itervalues()))

Or print all available items:

for k, val in shop_items.iteritems():
    pri,inv = val["price"],val["inventory"]
    print("We have {} {}'s available at a price of ${} per unit".format(inv,k,pri))

We have 32 orange's available at a price of $1.5 per unit
We have 15 pear's available at a price of $3 per unit
We have 6 banana's available at a price of $4 per unit
We have 0 apple's available at a price of $2 per unit

If you are dealing with money you should really use the decimal library.