开发者

Python: has_key , I want to print the value of the key with if statement

could you please help me with this.

I want to print the value of开发者_运维知识库 the key with if statement. it is have one OR other value if it is not , but not for one , for all.

my try:

wp = {'tomatos': , 'patotoes': , 'milk':0.5'cheese':, 'eggs':0.25,'meat':2}
x= ' item is not available in this store'

how I can make my output like this ?

tomatos item is not available in this store.

patotoes item is not available in this store.

milk 0.5

cheese item is not available in this store .

eggs 0.25

meat 2

thats mean if any Item in the list dont have price , print x infront of it , and for others print the price shown .


There are tons of ways to do what you are asking but the below would work:

wp = { 'tomatos': None,
       'patotoes': None ,
       'milk':0.5,
       'cheese': None, 
       'eggs':0.25,
       'meat':2}
x= ' item is not available in this store'

for k,v in wp.items():
   print "%s%s" % (k, (v if v is not None else x))

Please not the changes to wp.


Use the fact that the 'get' method of a dictionary returns None (by default) for a key that's not in the dictionary.

itemPrices = { 'milk' : 0.5, 'eggs' : 0.25, 'meat' : 2.0 }
sorry = 'Sorry, %s is not available in this store.'

for itemName in ('milk', 'potatos', 'eggs'):
    price = itemPrices.get(itemName)
    if price is None:
        print sorry % itemName
    else:
        print itemName, price
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜