【发布时间】:2017-12-18 19:56:30
【问题描述】:
我已经发布了一个类似的问题,但我没有得到正确的答案,可能是因为我不太清楚我希望我的程序运行的方式。
我正在编写一个简单的礼物添加程序,我想在不同功能的字典中添加礼物给一个人。
def main():
print("Select: ")
print("\n\n\t1. Gifts")
selection_1 = input()
if selection_1 == "1":
people_list()
return selection
else:
print("Type a number for selecting.")
main()
def people_list():
people = {"Elena":["book","candy","sweater"],
"Daria":["healthy food"],
"Petra and Rok":[],
"Nikola":["cheese"],
"Matija + Elena":["vacation"],
"Christian":["chocolate"]}
print ("""Select a person to show their gifts:
1. Elena
2. Daria
3. Petra and Rok
4. Nikola
5. Matija + Elena
6. Christian
""")
gifts(people)
def gifts(people):
selection_2 = input()
if selection_2 == "1":
person = people["Elena"]
print(people["Elena"])
manage_gifts(person, people)
return person
elif selection_2 == "2":
person = people["Daria"]
print(people["Daria"])
manage_gifts(person, people)
return person
elif selection_2 == "3":
person = people["Petra and Rok"]
print(people["Petra and Rok"])
manage_gifts(person, people)
return person
elif selection_2 == "4":
person = people["Nikola"]
print(people["Nikola"])
manage_gifts(person, people)
return person
elif selection_2 == "5":
person = people["Matija + Elena"]
print(people["Matija + Elena"])
manage_gifts(person, people)
return person
elif selection_2 == "6":
person = people["Christian"]
print(people["Christian"])
manage_gifts(person, people)
return person
else:
print("Choose a person from the list!")
people_list()
return person
def manage_gifts(person, people):
print("""
1. Add gift""")
gift_option = input()
if gift_option == "1":
print("\nType the gift you would like to add?\n")
new_gift = input()
people[person].append(str(new_gift))
print("Gift added: ", people[person])
main()
我希望将新礼物添加到我从列表中选择的“人”中。 我得到的错误是:
Traceback (most recent call last):
File "E:/Python/Vaje_Book/Gifts.py", line 92, in <module>
main()
File "E:/Python/Vaje_Book/Gifts.py", line 10, in main
people_list()
File "E:/Python/Vaje_Book/Gifts.py", line 36, in people_list
gifts(people)
File "E:/Python/Vaje_Book/Gifts.py", line 46, in gifts
manage_gifts(person, people)
File "E:/Python/Vaje_Book/Gifts.py", line 89, in manage_gifts
people[person].append(str(new_gift))
TypeError: unhashable type: 'list'
非常感谢您的帮助。
【问题讨论】:
-
你应该在一些新的变量列表中获取值,然后附加 new_gift 然后更新它。顺便说一句,如果您想传递字典,请在定义函数 manage_gift 的参数中使用 **。
-
据我所知,您希望将
person = people["Elena"]中的gifts()更改为person = "Elena"等。您希望person只是一个供您查找的名称people。相反,people['Elena']将他们已经拥有的礼物还给你。
标签: python list function dictionary add