位置:- 正文

python如何将字典内容写入json文件(python如何将字典中的键值互换)

编辑:rootadmin

推荐整理分享python如何将字典内容写入json文件(python如何将字典中的键值互换),希望有所帮助,仅作参考,欢迎阅读内容。

文章相关热门搜索词:python如何将字典转成列表,python如何将字典中的键值互换,Python如何将字典中的值转化为列表,python如何将字典转成列表,python如何将字典中的键值互换,python如何将字典写入文件,Python如何将字典中的值转化为列表,python如何将字典写入文件,内容如对您有帮助,希望把文章链接给更多的朋友!

python将字典内容写入json文件的方法:我们可以先使用json.dumps()函数将字典转换为字符串;然后再将内容写入json即可。json.dumps()函数负责对数据进行编码。

python如何将字典内容写入json文件(python如何将字典中的键值互换)

字典内容写入json时,需要用json.dumps将字典转换为字符串,然后再写入。

(推荐教程:Python入门教程)

json也支持格式,通过参数indent可以设置缩进,如果不设置的话,则保存下来会是一行。

举例:

无缩进:

fromcollectionsimportdefaultdict,OrderedDictimportjsonvideo=defaultdict(list)video["label"].append("haha")video["data"].append(234)video["score"].append(0.3)video["label"].append("xixi")video["data"].append(123)video["score"].append(0.7)test_dict={'version':"1.0",'results':video,'explain':{'used':True,'details':"thisisforjosntest",}}json_str=json.dumps(test_dict)withopen('test_data.json','w')asjson_file:json_file.write(json_str)

有缩进:

fromcollectionsimportdefaultdict,OrderedDictimportjsonvideo=defaultdict(list)video["label"].append("haha")video["data"].append(234)video["score"].append(0.3)video["label"].append("xixi")video["data"].append(123)video["score"].append(0.7)test_dict={'version':"1.0",'results':video,'explain':{'used':True,'details':"thisisforjosntest",}}json_str=json.dumps(test_dict,indent=4)withopen('test_data.json','w')asjson_file:json_file.write(json_str)
本文链接地址:https://www.jiuchutong.com/zhishi/304534.html 转载请保留说明!
下一篇链接:https://www.jiuchutong.com/zhishi/304535.html
免责声明:网站部分图片文字素材来源于网络,如有侵权,请及时告知,我们会第一时间删除,谢谢! 邮箱:opceo@qq.com

鄂ICP备2023003026号

友情链接: 武汉网站建设 电脑维修 湖南楚通运网络