Python列表中的字典

时间:2013-06-05 17:39:21

标签: 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)

此代码没有,我只是希望它能够更改列表中的第二项(yaha)。

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.")

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:5)

我认为你的意思是

father[son][1] = description

在第二个片段中。

说明:

  • father是一个字典,son是一个字符串,因此son[father]会引发AttributeError
  • description也是一个字符串,因此description[1]是一个字符。另一方面,father[son]是一个列表,您可以将其元素分配给新字符串。

答案 1 :(得分:0)

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

因为description是一个字符串