简体   繁体   English

使用循环更新字典

[英]Dictionary update using a loop

I don't understand why my dictionary isn't updating.我不明白为什么我的字典没有更新。 If I enter two names, eg Joe and Josh , then I'd like the out put to be 'name : Joe, name: Josh' , but at the moment the result is 'name: Josh' .如果我输入两个名字,例如JoeJosh ,那么我希望输出为'name : Joe, name: Josh' ,但目前结果是'name: Josh'

How can I do this properly?我怎样才能正确地做到这一点?

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)

You are overwriting the content of the dict, as you are using always the same key.您正在覆盖字典的内容,因为您始终使用相同的键。 If you want to store your frinds in a list you could use a list of dicts:如果你想将你的朋友存储在一个列表中,你可以使用一个字典列表:

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)

With Joe and Josh you then get有了乔和乔希,你就会得到

[{'name': 'Joe'}, {'name': 'Josh'}]

Another idea would be make the names as keys另一个想法是将名称作为键

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)

With Joe and Josh you then get有了乔和乔希,你就会得到

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

Key values must be unique in a dictionary, but you have multiple "name" keys.键值在字典中必须是唯一的,但您有多个“名称”键。 I think what you want is a set, which will maintain one copy of each of the names you add to it.认为您想要的是一个集合,它将保留您添加到其中的每个名称的一个副本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM