[Tutor] Looping through Dictionaries

Mats Wichmann mats at wichmann.us
Tue May 23 14:47:25 EDT 2017


On 05/23/2017 11:38 AM, Rafael Knuth wrote:
> I wrote a function (shopping list) which calculates the total price of
> the purchase (quantity * price) as well as the stock change (stock -
> quantity). I know the latter is imperfect (my function does not take
> into account if items are out of stock for example, but that's my next
> challenge. The function does exactly what it's supposed to do:
> 
> def shopping(quantity, price, stock):
>     total = 0
>     for key in quantity:
>         total += quantity[key] * price[key]
>         stock_update = stock[key] - quantity[key]
>         print(stock_update)
>     print(total)
> 
> quantity = {
>     "bapple": 10,
>     "banana": 20
> }
> 
> price = {
>     "bapple": 5,
>     "banana": 3
> }
> 
> stock = {
>     "bapple": 20,
>     "banana": 50
> }
> 
> shopping(quantity, price, stock)
> 
> Now, I want to print the item next to the stock update, and I am
> receiving an error message. I couldn't figure out how to fix that:

in the code below you're trying to use "value" as your key, but it isn't
the key. Why did you change that from the code above?

it helps if you include the errors, by the way :)

> 
> def shopping(quantity, price, stock):
>     total = 0
>     for key, value in quantity.items():
>         total += quantity[value] * price[value]
>         stock_update = stock[value] - quantity[value]
>         print(key, stock_update)
>     print(total)
> 
> quantity = {
>     "bapple": 10,
>     "banana": 20
> }
> 
> price = {
>     "bapple": 5,
>     "banana": 3
> }
> 
> stock = {
>     "bapple": 20,
>     "banana": 30
> }
> 
> shopping(quantity, price, stock)
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> To unsubscribe or change subscription options:
> https://mail.python.org/mailman/listinfo/tutor
> 



More information about the Tutor mailing list