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

Python字典按顺序新增数字键时键被覆盖问题如何解决

喜爱城市字典新增条目键覆盖问题修复

问题表现

存储用户喜爱城市的字典结构为{用户名: {数字序号: 城市名}},需求是给指定用户新增城市时,新条目的数字键接续已有条目的最大序号递增。例如给用户Viktor原有{1:"Berlin",2:"Dresden"}基础上新增Hamburg、Dortmund两个城市,预期新键为3、4,实际运行出现键覆盖、序号错乱,原有Berlin条目丢失,错误输出如下:

Favorite cities: Viktor
1, Dortmund
2, Dresden
0, Hamburg

问题复现代码:

dict={"Viktor":{1:"Berlin",2:"Dresden"},"Joe":{1:"London",2:"Liverpool"}}

name=input("What is your name? ").title()
if name not in dict:
  print("You are not in the database.")
  exit()
q = input("Enter how many your favorite cities you want to add ")
if q.isdigit():
  q = int(q)
  for d in range(q):
    fav_city = input("Enter your favorite city: ")
    dict[name][d] = fav_city
    print(fav_city, "added")

  for person, city in dict.items():
    print(f"Favorite cities: {person}")
    for nummer, city1 in city.items():
      print(f"{nummer}, {city1}\n")
else:
  print("Enter a digit!")
  exit()

错误原因

  • 新增条目时使用for d in range(q)生成序号,range(q)默认从0开始计数,输入新增2个城市时循环变量d依次为0、1,直接把用户原有键为1的Berlin数据覆盖成第二个输入的Dortmund。
  • 代码完全没有读取用户已有条目的最大序号,新序号没有做接续逻辑,从0开始生成的键既会和旧键冲突,也不符合序号连续递增的预期。
  • 存在隐性bug:使用Python内置字典类型名dict作为自定义变量名,会覆盖内置类的引用,容易引发其他不可预期的错误。

修正代码

核心修改逻辑:

  • 将原变量名dict改为fav_city_db,避免覆盖内置类型
  • 新增城市前先计算对应用户现有城市条目的最大键值,新序号从最大键+1开始递增
  • 保留原有输入校验、输出逻辑不变
fav_city_db = {"Viktor":{1:"Berlin",2:"Dresden"},"Joe":{1:"London",2:"Liverpool"}}

name = input("What is your name? ").title()
if name not in fav_city_db:
    print("You are not in the database.")
    exit()
q = input("Enter how many your favorite cities you want to add ")
if q.isdigit():
    q = int(q)
    # 计算当前用户已有条目的最大序号,无条目时从0开始计数
    current_max_key = max(fav_city_db[name].keys()) if fav_city_db[name] else 0
    for offset in range(q):
        new_key = current_max_key + 1 + offset
        fav_city = input("Enter your favorite city: ")
        fav_city_db[name][new_key] = fav_city
        print(fav_city, "added")

    for person, city_map in fav_city_db.items():
        print(f"Favorite cities: {person}")
        for nummer, city_name in city_map.items():
            print(f"{nummer}, {city_name}\n")
else:
    print("Enter a digit!")
    exit()

修正后给Viktor新增2个城市的输出符合预期,原有数据不会丢失,新序号连续递增:

Favorite cities: Viktor
1, Berlin
2, Dresden
3, Hamburg
4, Dortmund

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 17:18:05