2015-11-08 70 views
0

所以我想調用一個字典中的字典並使用這些鍵作爲值,但是我所有嘗試達到它的失敗迄今爲止。這是我的位置,請注意,if表達式之後的所有打印語句都會失敗。字典中的字典調用

def main(): 
    print("This program tells you about the animal of your choice") 
    animal=input("What animal would you like to look up: ") 
    animal=animal.lower() 

    d2={ 
     "lion":{"name":"Lion","species":"Panthera leo", 
     "image":"http://en.wikipedia.org/wiki/File:Lion_waiting_in_Namibia.jpg", 
     "fact":"Vulnerable species"}, 
    "dog":{"name:":"Dog","species":"Canis lupus familiaris", 
     "image":"http://en.wikipedia.org/wiki/File:YellowLabradorLooking_new.jpg", 
     "fact":"Common house pet"}, 
     "hippo":{"name":"Hippo","species":"Hippopotamus amphibius", 
        "image":"https://en.wikipedia.org/wiki/Hippopotamus#/media/File:Hippopotamus_-_04.jpg", 
        "fact":"Erbivorous mammal"}, 
     "cat":{"name":"Cat","species":"Felis catus", 
       "image":"https://en.wikipedia.org/wiki/Cat#/media/File:Cat_poster_1.jpg", 
       "fact":"Purring hunters"} 
     } 
    if animal in d2: 
     print(d2(animal["name"]), "is the common name") 
     print(d2(animal["species"]), "is its latin name") 
     print(d2(animal["image"]), "is a picture of", animal) 
     print(d2(animal["fact"]),) 
    else: 
     print("Not in dicionary, try lion, dog, hippo, or cat") 
main() 
+0

當我粘貼代碼時,某些縮進消失,所以這就是爲什麼文本看起來如此混亂在d2 – Magnus

+1

'dict'元素由'[​​]'而不是'()'訪問。 – sobolevn

+0

您是否注意到您使用圓括號代替方括號來訪問字典? – TigerhawkT3

回答

3

當你這樣做:

print(d2(animal["name"]), "is the common name") 

表示你是治療d2的功能。相反,嘗試

animal_dict = d2.get(animal, {}) 
animal_name = animal_dict.get("name") 
print("%s is the common name" % animal_name) 

等..

+0

你不需要在Python 3中的'.keys()' – TigerhawkT3

+0

不同意你的第一個stmt ...如果動物在d2是相同的,如果d2.keys中的動物()和d2中的動物是首選和簡潔的。 – labheshr

+0

同意! Python2也是如此。我的意思是最好明確:) – karthikr

1

這很簡單,因子評分。請參閱...

print(d2(animal["name"]), "is the common name") 

這意味着「打印調用d2(跟單參數作爲在animal指數"name"的對象)和字符串"is the common name"的返回值」。

這沒有任何意義,不是嗎?您不能使用圓括號(呼叫操作員,())來「調用」字典。這對你有意義嗎? IHMO,這沒有任何意義。

相反,你應該索引與密鑰animal字典。但是,從顯示的內容根據意見已經發生了,你想這...

d2[animal["name"]] 

這意味着:「在對象指數d2(索引"name"animal對象)」。再一次,這是沒有意義的。正確的方法是...

d2[animal]["name"] 

這意味着「在d2指數"name"的對象,在指數animal對象」。現在,這是有道理的!您應該將相同的更改模式應用於所有打印語句。

爲什麼會發生這種情況? d2是詞典的詞典。因此...

x = d2[animal] 

意思是 「儲存在xd2索引animal對象」。然後......

x["name"] 

辦法 「在x指數"name"對象」。現在,這對你有意義嗎? )。

編輯:對於那些由歷史原因誤導,(幾乎)從未使用在Python 2.x的input(),除非你知道你在做什麼!改用raw_input()(相同的界面)。

我希望這能帶給你一些亮點!

+0

是的,謝謝。然而,使用你的方法會給我一個名字上的KeyError ...你確定我可以寫print(d2 [animal] [「name」]) – Magnus

+0

@ M.gnus:如果你在Python2上,使用'raw_input() ',而且從不**使用'input()'(除非你在Python3中)。 – 3442