【发布时间】:2020-04-08 12:16:19
【问题描述】:
所以我有一个基本的user.json 文件。
我的问题是:如何将另一个字典添加到我的 JSON 列表中?
下面是我的代码,如您所见,我尝试了这个:append、update、insert,但我找不到任何工作结果。目标是能够添加一个新的:
NAME: name1 // COUNTRY: coutry1 // GENDER: gender1... 到人员 JSON 列表...谢谢。 Python 代码
import json
with open("user.json") as f:
data = json.load(f)
new_dict = {"name": "name1",
"Country": "Country2",
"Gender": "Gender3"}
for person in data["person"]:
person.update(new_dict)
with open("user.json", "w") as f:
json.dump(data, f, indent=2)
user.json
{
"person": [
{
"name": "Peter",
"Country": "Montreal",
"Gender": "Male"
},
{
"name": "Alex",
"Country": "Laval",
"Gender": "Male"
},
{
"name": "Annie",
"Country": "Quebec",
"Gender": "Female"
},
{
"name": "Denise",
"Country": "Levis",
"Gender": "Female"
}
]
}
【问题讨论】:
标签: python json list dictionary append