You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python使用while循环录入数据存字典时丢失重复键旧值问题

问题原因

Python 字典的键(key)具备唯一性约束,当对已经存在的键重复执行赋值操作时,新值会直接覆盖该键对应的旧值。你代码中的cars[models] = colors逻辑,在两次录入车型均为bmw时,第二次赋值直接覆盖了第一次存入的red值,因此最终字典中仅保留了最后一次录入的blue值。

可选优化方案

如果需要保留同一车型的所有录入记录,可将字典的值设为列表类型,每次录入时向列表追加数据而非直接覆盖,示例代码如下:

cars = {}

while True:
    models = input('Please enter car model name: ')
    colors = input('Please enter car color: ')
    # 车型不存在时先初始化空列表
    if models not in cars:
        cars[models] = []
    cars[models].append(colors)
    another = input('Do you want to register another car? (y/n): ')
    if another == 'y':
        continue
    else:
        break

print(cars)

对应你的测试输入,运行后输出结果为:

{'bmw': ['red', 'blue'], 'merc': ['black']}

内容的提问来源于stack exchange,提问作者Ridzwan Radzi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 03:42:01