将dict添加到现有键值时出现此错误

  • 本文关键字:错误 键值 dict 添加 python json
  • 更新时间 :
  • 英文 :


包含JSON文件代码的代码:Python(假设附加一个新用户和余额(:

import json
with open('users_balance.json', 'r') as file:
data = json.load(file)['user_list']
data['user_list']
data.append({"user": "sdfsd", "balance": 40323420})
with open('users_balance.json', 'w') as file:
json.dump(data, file, indent=2)

Json(代码附加的对象(:

{
"user_list": [
{
"user": "<@!672986823185661955>",
"balance": 400
},
{
"user": "<@!737747404048171043>",
"balance": 500
}
],
}

错误(执行代码后出现回溯错误(:

data = json.load(file)['user_list']
KeyError: 'user_list'

解决方案如下:

import json
with open('users_balance.json', 'r') as file:
data = json.load(file) 
data['user_list'].append({"user": "sdfsd", "balance": 40323420})
with open('users_balance.json', 'w') as file:
json.dump(data, file, indent=2)

最新更新