简体   繁体   中英

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' .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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