Dictionary update using a loop to insert the same key multiple times is only inserting the last value

Question:

I don’t understand why my dictionary isn’t updating. If I enter two names, e.g. 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)
Asked By: Joshua Dunn

||

Answers:

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.

Answered By: Mark Lavin

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'}
Answered By: user_na
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.