2

Now i know there is some coverage of this topic already but i can't understand it. I'll show you my code and i hope this helps you understand where i'm at.

Dictionary

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

This code works fine.

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)

This code doesn't, I just want it to be able to change the second item in the list(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.")

Any help would be appreciated.

4

2 回答 2

5

我想你的意思是

father[son][1] = description

在第二个片段中。

解释:

  • father是一个字典,son是一个字符串,所以son[father]会引发一个AttributeError.
  • description也是一个字符串,description[1]单个字符也是。father[son]另一方面,它是一个列表,您可以将其元素分配给一个新字符串。
于 2013-06-05T17:44:26.873 回答
0
description = input("What's name of the grandfather?: ")
son[father] = description

因为描述是一个字符串

于 2013-06-05T17:45:24.767 回答