加载一个 json 文件,循环访问它并将每个元素写入新文件



我有一个json文件,现在我想修改(更改密钥(该json文件。我能够通读该文件中的每个项目,但不知道如何使用 Python 修改在新字典中编写它

目前 json 文件是这样的:

[
{"detail": ["Jishnu Prasad Rijal ", " Biratnagar , Morang,", "M", "BBS, India", "1"]},
{"detail": ["Lakshmishwar Prasad ", " Kharihani , Dhanusa,", "M", "BBS, India", "2"]},
]

但我想要这种格式:

[{
"name":"Jishnu Prasad Rijal","roll_no":1,"gender":"Male",
"address":"Biratnagar,Morang","degree":"BBS, India"
}, {
"name":"Lakshmishwar Prasad ","roll_no":2,"gender":"Male",
"address":"Kharihani , Dhanusa","degree":"BBS, India"
}]

帮助将不胜感激。 谢谢

只需使用zip

keys = ['name', 'address', 'gender', 'degree', 'role_no']
x = [dict(zip(keys, i['detail'])) for i in x]
[{'name': 'Jishnu Prasad Rijal ', 'address': ' Biratnagar , Morang,', 'gender': 'M', 'degree': 'BBS, India', 'role_no': '1'}, {'name': 'Lakshmishwar Prasad ', 'address': ' Kharihani , Dhanusa,', 'gender': 'M', 'degree': 'BBS, India', 'role_no': '2'}]
input_dict = [
{"detail": ["Jishnu Prasad Rijal ", " Biratnagar , Morang,", "M", "BBS, India", "1"]},
{"detail": ["Lakshmishwar Prasad ", " Kharihani , Dhanusa,", "M", "BBS, India", "2"]},
]
cols = ['name','address','gender','degree','roll_no']
output_list = []
for el in input_dict:
x = el['detail']
#print(dict(zip(cols,x)))
op = dict(zip(cols,x))
output_list.append(op)
print(output_list)

最新更新