2013-11-28 43 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