2013-06-05 192 views
2

現在我知道這個主題已經有一些報道了,但我無法理解它。我會告訴你我的代碼,我希望這可以幫助你理解我在哪裏。詞典中的Python列表

字典

father = {"Yin": ["yang","yaha"]} 

此代碼工作正常。

elif choice == "5": 
    son = input("Enter the name of a son to get the name of his grandfather: ") 
    if son in father: 
     description = father[son] 
     print("\n", son, "'s grandfather is", description[1]) 
    else: 
     print("\nSorry, I don't know who that is", son) 

此代碼不,我只是希望它能夠改變在列表中(牙哈)的第二項。

elif choice == "6": 
    son = input("which grandfather and son pair need updating: ") 
    if son in father: 
     description = input("What's name of the grandfather?: ") 
     son[father] = description[1] 
     print("\n", son, "has been redefined.") 
    else: 
     print("\nThat person doesn't exist! Try adding it.") 

任何幫助,將不勝感激。

回答

5

我想你的意思

father[son][1] = description 
在第二個片段

說明:

  • father是一個字典,son是一個字符串,所以son[father]將引發AttributeError。因爲description[1]是單個字符。另一方面,father[son]是一個列表,您可以將其元素分配給一個新的字符串。
+0

OMG!謝謝你,我幾乎在其他地方嘗試過[1]。 –

+1

@jimmyLight不客氣:)考慮[接受答案](http://meta.stackexchange.com/a/5235/181223)如果它解決了這個問題。 –

0
description = input("What's name of the grandfather?: ") 
son[father] = description 

因爲描述是一個字符串