Python:has_key,如何使用if语句打印键的值
你能帮我一下吗?
我想用if语句来打印某个键的值。如果这个键没有值,就打印一个提示,但不是只针对一个,而是针对所有的。
这是我尝试的代码:
wp = {'tomatos': , 'patotoes': , 'milk':0.5'cheese':, 'eggs':0.25,'meat':2}
x= ' item is not available in this store'
我该怎么做才能让输出结果像这样呢?
番茄在这个商店里没有货。
土豆在这个商店里没有货。
牛奶 0.5
奶酪在这个商店里没有货。
鸡蛋 0.25
肉 2
这意味着如果列表中的任何项目没有价格,就在它前面打印一个x,对于其他有价格的项目则打印出显示的价格。
2 个回答
1
可以利用字典的'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
2
有很多方法可以实现你想要的效果,但下面这个方法是可行的:
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
的修改。