How i print prices keys correctly? in A Day at the Supermarket


#1
prices = {
    'banana': 4,
    'apple': 2,
    'orange': 1.5,
    'pear': 3,
    
}

stock = {
    'banana': 6,
    'apple': 0,
    'orange': 32,
    'pear': 15,
}

for keys in prices:
    count = 0
    print(prices.keys()[count += 1]) # this line report an error, but i can't know what's wrong.
    print('Price: %s' % prices[keys])
    print('Stock: %s' % stock[keys])

#2

What you have there is some goofiness.

Here is a list of thy issues!

  1. Scope: once a loop is done the count is garbage collected, thus starting fresh each time!
  2. Dict Keys is not a dict so it does not support the keys() method

Ok so let's work on this.

for key, value in prices.items():
    print(key)
    print('Price: %s' % value)
    print('Stock: %s' % stock[key])

Simple as that!

Now as to why this works, python will automagically look at the key, value of a dict when used like this.

Now if you really, really wanted to access the dict directly you would need to do the following for a more pythonic way.

list_of_items = ['apple', 'banana', 'orange', 'pear']
for item in list_of_items:
    print(item)
    print('Price: %s' % prices[item])
    print('Stock: %s' % stock[item])

#3

Thank you :smile:

For me only works this way:

for item in prices and stock:

    print item #Prints the name

    print "price: " + str(prices[item]) #Prints the price

    print "stock: " + str(stock[item]) #Prints the stock