如何在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)
代码说明
- 输入类型转换:把用户输入的增量从字符串转为整数,确保能正常执行加法运算
- 字典数据更新:通过用户选择的地区名称,直接定位到字典中对应条目,完成数值累加
- 结果输出:打印更新后的
city字典,与预期输出一致 - 文件同步(可选):如果需要让本地文件的内容也保持最新,将字典数据重新整理为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
相关产品推荐
相关产品推荐

