简体   繁体   中英

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, eg "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?

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.

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]

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 (ieeg False or [] or None ), then the expressions resolves to X . Only if X is not falsy (ieeg 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 []
[]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM