You need to enable JavaScript to run this app. Python循环调用update插入同键字典仅保留最后值如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Python循环调用update插入同键字典仅保留最后值如何解决

故障原因
  • Python字典的键具有全局唯一性,你的代码中每次循环都使用name作为固定键调用update()方法,新值会直接覆盖旧的同键值,最终只会保留最后一次输入的姓名。
  • 额外优化点:input()返回值本身就是字符串类型,不需要额外套str()做类型转换,属于冗余代码。
修复后代码
# 用列表存储多个姓名字典,避免同键覆盖
names_container = []
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):
        name = input().strip()
        names_container.append({'name': name})
    # 拼接成你需要的输出格式
    output_content = ', '.join([f'name: {item["name"]}' for item in names_container])
    print(output_content)
可选方案(必须用字典存储的场景)

如果业务要求必须用字典结构存储,可以给键加上唯一后缀避免重复,逻辑示例:

names_dic = {}
for i in range(num_people):
    name = input().strip()
    # 键名拼接序号保证唯一性
    names_dic[f'name_{i+1}'] = name

该场景下列表存储的扩展性更强,后续做增删改查操作更便捷。

效果验证

输入2,依次输入Joe和Josh,输出结果为:name: Joe, name: Josh,完全符合预期。

内容的提问来源于stack exchange,提问作者Joshua Dunn

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.14 07:36:08