[Tutor] Looping through Dictionaries

Alan Gauld alan.gauld at yahoo.co.uk
Tue May 23 14:45:36 EDT 2017


On 23/05/17 18:38, Rafael Knuth wrote:

> 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:

So show us the error message, all of it.
I can't begin to guess what it might be.

UI also don't understand what "print the
item next to the stock update" means.
Do you mean the actual location of the
data in the printed string? Or do you
mean the value(which?) next to the one
in your function?

Can you show us some examples?


> def shopping(quantity, price, stock):
>     total = 0
>     for key, value in quantity.items():
>         total += quantity[value] * price[value]
>         stock_update = stock[value] - quantity[value]

I don't see how this would work. value is the value
from the dictionary which is an integer. But you are
using it as a key which should be a string?
So in your first iteration key,value will be
key = 'bapple', value=10

so you are trying to evaluate

stock[10]-quantity[10]

but thee are no such items.

I suspect you mean:

stock['bapple'] - quantity['bapple']

or in your function:

stock[key] - quantity[key]

But in that case you don;t need the value from items()
you can just iterate over the keys:

for item in quantity:
    ...
    stock_update = stock[item] - quantity[item]
    print(item, stock_update)

>         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)

I'm not clear on what these variables indicate.
What is the difference between quantity and stock?

Also this might be a good time to look at classes
and objects. You could avoid all the multiple
stores by putting the various data elements
in a class.  This would avoid the potential
headaches caused by mis-typing the item names
in each store, for example. You could then
have variables bapple and banana and access,
for example, bapple.quantity and bapple.price.
And just keep a simple list of items.
Just a thought...

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list