2013-11-28 105 views
0

我试图从用户输入的密钥中打印出字典中的值,但没有出现。有任何想法吗?为什么这不是在字典中打印出一个值?

u_items=input("Enter 'list' to see a list of items, or 'Book', 'Apple', 'Toy', 'Pumpkin', 'Bowl' or 'Purse' to see the item's price: ") 
u_items=u_items.title() 

inventory={'Book':'18', 'Apple':'3', 'Toy':'7', 'Pumpkin':'9', 'Bowl':'5', 'Purse':'30'} 

if u_items in inventory[u_items] == True: 
    print("A " + u_items + "costs $" + inventory[u_items]) 

elif u_items == 'List': 
    print(items(inventory)) 
+0

什么是'title()'? – MxyL

+0

@Keikoku - 使字符串像书名一样的字符串方法。要亲自看看,请在解释器中运行:''happy birthday'.title()'。或者,这里是[docs](http://docs.python.org/2.7/library/stdtypes.html#str.title)。 – iCodez

+0

@iCodez哦,这很酷..我想。不看起来像一个非常聪明的转换器,但我想它的工作...... – MxyL

回答

1

您的if语句构造错误。它应该是这样的:

if u_items in inventory: 

此测试,如果u_items(用户输入的密钥)存在于词典中。

你之前在做什么看到u_items是否存在于索引inventoryu_items返回的值中。因此,如果用户输入'apple',您的代码将被解释为:

if 'Apple' in '3' == True: 
+0

谢谢你多! – rs19

+0

和项目[库存]不起作用。猜测我的语法错了? – rs19

+0

@ rs19 - 嗯,是的。我错过了。 'item'是'dict'的一种方法,所以你应该这样做:'inventory.items()' – iCodez

相关问题