[英]Python: has_key , I want to print the value of the key with if statement
你能帮我解决这个问题吗?
我想用 if 语句打印键的值。 如果不是,则它具有一个或其他值,但不是为一个,为所有。
我的尝试:
wp = {'tomatos': , 'patotoes': , 'milk':0.5'cheese':, 'eggs':0.25,'meat':2}
x= ' item is not available in this store'
我怎样才能让我的 output 像这样?
这家商店没有番茄商品。
这家商店没有 patotoes 商品。
牛奶 0.5
这家商店没有奶酪项目。
鸡蛋 0.25
肉 2
这意味着如果列表中的任何项目没有价格,请在其前面打印 x,其他人则打印显示的价格。
有很多方法可以满足您的要求,但以下方法可行:
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))
请不要更改wp
。
使用字典的“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.