RikuSoulz
RikuSoulz

Reputation: 27

Looping a dictionary and printing the values?

I'm asking here again 'cause I don't know how to do this... I have this code:

prices={'banana':4, 'apple':2, 'orange':1.5, 'pear':3}
stock={'banana':6, 'apple':0, 'orange':32, 'pear':15}

for e in prices and stock:
    print e
    print "price: " + str(e)
    print "stock: " + str(e)

and in

print "price: " + str(e)
print "stock: " + str(e) 

I want to loop and print the value, e.g "1.5" in price and "32" in stock, but it prints the key, "orange" and I don't know how to loop and print the value of all the dictionary, can you please help me?

Upvotes: 0

Views: 890

Answers (3)

Martijn Pieters
Martijn Pieters

Reputation: 1121484

You need to loop over just one of the dictionaries, and use mapping access to print the values:

for e in prices:
    print e
    print "price:", prices[e]
    print "stock:", stock[e]

The above, however, will raise a KeyError if there are keys in prices that are not present in the stock dictionary.

To ensure that the keys exist in both dictionaries, you can use dictionary views to get a set intersection between the two dictionary key sets:

for e in prices.viewkeys() & stock:
    print e
    print "price:", prices[e]
    print "stock:", stock[e]

This will loop over only those keys that are present in both dictionaries.

Upvotes: 2

Hyperboreus
Hyperboreus

Reputation: 32429

prices and stocks resolves either to prices or to stocks, but never to the concatenation of both.

This is how it works: Python does layz evaluation of X and Y. First it looks at X and if it is falsy (i.e. e.g. False or [] or None), then the expressions resolves to X. Only if X is not falsy (i.e. e.g. True or [1,2] or 42) it returns Y.

Some examples:

>>> 2 and 3
3
>>> [] and 3
[]
>>> 2 and 'hello'
'hello'
>>> [] and 'hello'
[]
>>> [] and None
[]
>>> 42 and []
[]

Upvotes: 0

Manny D
Manny D

Reputation: 20714

Assuming the keys are always the same between prices and stock you can simply do this:

for key in prices:
   print key
   print "price: " + prices[key]
   print "stock: " + stock[key]

Upvotes: 0

Related Questions