首页 > 解决方案 > 使用循环更新字典

问题描述

我不明白为什么我的字典没有更新。如果我输入两个名称,例如Joeand 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)

标签: pythonloopsdictionary

解决方案


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

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)

有了乔和乔希,你就会得到

[{'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': 'Joins the party', 'Josh': 'Joins the party'}

推荐阅读