python - 使用循环更新字典
问题描述
我不明白为什么我的字典没有更新。如果我输入两个名称,例如Joe
and 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)
解决方案
您正在覆盖字典的内容,因为您始终使用相同的键。如果你想将你的朋友存储在一个列表中,你可以使用一个字典列表:
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'}
推荐阅读
- sql - 在 SQL 中捕获 200 天的支出窗口开始日期
- c - 如果它是零,我们为什么要乘以 10
- javascript - 拒绝加载图像“http://localhost:5000/favicon.ico”
- php - Codeigniter 事务未捕获错误
- c# - Unity - 精灵在场景视图中消失,但不是游戏视图
- ios - Mapbox:仅当注释在屏幕上可见时才添加注释
- reactjs - 尝试解决 React Context 的问题
- node.js - 定位 EJS 常量并将其传递给帖子
- typescript - “ChildNode”类型缺少“HTMLOptionElement”类型的以下属性
- html - 谷歌搜索引擎 API