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

如何在Python字典中实现地区人口与儿童数量的增量更新?

实现步骤及修改后的代码

核心修改点

  • 将输入的增量转换为整数类型,避免运算错误
  • 更新city字典中对应地区的人口和儿童数量
  • 可选:将更新后的数据写回area.txt,保证数据持久化

修改后的完整代码

area="""AREA,POPULATION,CHILD
ARKANSAS,2000,20
TEXAS,50,5"""
def createFiles():
    x = open('area.txt','w')
    x.write(area)
    x.close()
createFiles()


city = {}
total = 0
with open('area.txt', 'r') as file:
    next(file)
    for line in file:
        data = line.strip().split(',')
        place = data[0]
        city[place] = {}
        city[place]['Population'] = int(data[1])
        city[place]['Children'] = int(data[2])
print(city)
choose=input('Choose area ARKANSAS/TEXAS: ')
addPopu=int(input('Add population: '))
addChild=int(input('Add Children: '))

# 更新字典中对应地区的数据
city[choose]['Population'] += addPopu
city[choose]['Children'] += addChild

# 打印更新后的结果
print(city)

# 可选:将更新后的数据同步写入area.txt文件
with open('area.txt', 'w') as file:
    file.write("AREA,POPULATION,CHILD\n")
    for area_name, info in city.items():
        line = f"{area_name},{info['Population']},{info['Children']}\n"
        file.write(line)

代码说明

  1. 输入类型转换:把用户输入的增量从字符串转为整数,确保能正常执行加法运算
  2. 字典数据更新:通过用户选择的地区名称,直接定位到字典中对应条目,完成数值累加
  3. 结果输出:打印更新后的city字典,与预期输出一致
  4. 文件同步(可选):如果需要让本地文件的内容也保持最新,将字典数据重新整理为CSV格式写入area.txt,下次读取时会直接加载更新后的数据

运行示例输出

{'ARKANSAS': {'Population': 2000, 'Children': 20}, 'TEXAS': {'Population': 50, 'Children': 5}}
Choose area ARKANSAS/TEXAS: TEXAS
Add population: 10
Add Children: 5
{'ARKANSAS': {'Population': 2000, 'Children': 20}, 'TEXAS': {'Population': 60, 'Children': 10}}

内容的提问来源于stack exchange,提问作者Griffin De Leon

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.05 03:05:50