简体   繁体   English

Python:has_key,我想用if语句打印key的值

[英]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.我想用 if 语句打印键的值。 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?我怎样才能让我的 output 像这样?

tomatos item is not available in this store.这家商店没有番茄商品。

patotoes item is not available in this store.这家商店没有 patotoes 商品。

milk 0.5牛奶 0.5

cheese item is not available in this store.这家商店没有奶酪项目。

eggs 0.25鸡蛋 0.25

meat 2肉 2

thats mean if any Item in the list dont have price, print x infront of it, and for others print the price shown.这意味着如果列表中的任何项目没有价格,请在其前面打印 x,其他人则打印显示的价格。

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 .请不要更改wp

Use the fact that the 'get' method of a dictionary returns None (by default) for a key that's not in the dictionary.使用字典的“get”方法对不在字典中的键返回 None (默认情况下)这一事实。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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