【问题标题】:Dictionary update using a loop使用循环更新字典
【发布时间】:2021-06-27 17:45:30
【问题描述】:

我不明白为什么我的字典没有更新。如果我输入两个名字,例如JoeJosh,那么我希望输出为'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


【解决方案1】:

您正在覆盖字典的内容,因为您始终使用相同的键。如果您想将您的朋友存储在一个列表中,您可以使用一个字典列表:

names_list = []
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())
        names_list.append({'name': names})
print(names_list)

Joe 和 Josh 你会得到

[{'name': 'Joe'}, {'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 = {names: 'Joins the party'}
        names_dic.update(another_dict)
print(names_dic)

Joe 和 Josh 你会得到

{'Joe': 'Joins the party', 'Josh': 'Joins the party'}

【讨论】:

  • 非常感谢您这么快回复我!您的回答非常有帮助
【解决方案2】:

键值在字典中必须是唯一的,但您有多个“名称”键。我认为您想要的是一个集合,它将保留您添加到其中的每个名称的一个副本。

【讨论】:

  • 为什么要设置一个列表?如果两个朋友同名怎么办?
猜你喜欢
  • 2021-12-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-09
  • 2021-03-24
  • 2018-01-26
  • 2018-09-29
相关资源
最近更新 更多