import json years = [2020,2019,2018,2017,2016] incomes = { '北京市':[5483.89,5817.10,5785.92,5430.79,5081.26], '天津市':[1923.05,2410.41,2106.24,2310.36,2723.50], '上海市':[7046.30,7165.10,7108.15,6642.26,6406.13], '重庆市':[4257.98,4070.83,3911.01,3577.99,3388.85] } dora = {'years:',years,'incomes:',incomes} with open("IncomesData.json","wt") as f: json.dump('dora',f) with open("IncomesData.json","rt") as f: doraLoaded = json.load(f) for key,value in doraLoaded.items(): print(key,":",value)哪里有错
时间: 2023-11-14 13:06:08 浏览: 193
Oracle面试题及答案整理.docx
代码中有两个错误:
1. 在构造字典 `dora` 时,应该直接将 `years` 和 `incomes` 作为值,而不是用字符串包裹它们。正确的写法应该是:
```
dora = {'years': years, 'incomes': incomes}
```
2. 在将字典 `dora` 写入 JSON 文件时,应该写入字典本身,而不是字符串 `'dora'`。正确的写法应该是:
```
json.dump(dora, f)
```
修改后的完整代码如下:
```
import json
years = [2020, 2019, 2018, 2017, 2016]
incomes = {'北京市': [5483.89, 5817.10, 5785.92, 5430.79, 5081.26],
'天津市': [1923.05, 2410.41, 2106.24, 2310.36, 2723.50],
'上海市': [7046.30, 7165.10, 7108.15, 6642.26, 6406.13],
'重庆市': [4257.98, 4070.83, 3911.01, 3577.99, 3388.85]}
dora = {'years': years, 'incomes': incomes}
with open("IncomesData.json", "wt") as f:
json.dump(dora, f)
with open("IncomesData.json", "rt") as f:
doraLoaded = json.load(f)
for key, value in doraLoaded.items():
print(key, ":", value)
```
阅读全文