【发布时间】:2021-06-27 17:45:30
【问题描述】:
我不明白为什么我的字典没有更新。如果我输入两个名字,例如Joe 和Josh,那么我希望输出为'name : Joe, name: Josh',但目前结果为'name: Josh'。
我怎样才能正确地做到这一点?
names_dic = {}
print("Enter the number of friends joining (including you):")
num_people = int(input())
print("Enter the name of every friend (including you), each on a new line:")
if num_people == 0:
print("No one is joining for the party")
else:
for _ in range(num_people):
names = str(input())
another_dict = {'name': names}
names_dic.update(another_dict)
print(names_dic)
【问题讨论】:
-
字典不能有重复的键。
-
这看起来应该只是一个列表,而不是字典。
-
你应该使用列表,因为你的用例不反映 dict 的任何用处。也不需要使用
.update,你可以简单地输入your_dict[key]=value。在这两种情况下,这里的关键是name。由于 dict 不包含重复键,因此您将留下name:josh,因为它是第一次更新的。
标签: python loops dictionary