新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
創(chuàng)新互聯(lián)Python教程:python如何將字典內容寫入json文件
python將字典內容寫入JSON文件的方法:我們可以先使用json.dumps()函數(shù)將字典轉換為字符串;然后再將內容寫入json即可。json.dumps()函數(shù)負責對數(shù)據(jù)進行編碼。

字典內容寫入json時,需要用json.dumps將字典轉換為字符串,然后再寫入。
(推薦教程:Python入門教程)
json也支持格式,通過參數(shù)indent可以設置縮進,如果不設置的話,則保存下來會是一行。
舉例:
無縮進:
from collections import defaultdict, OrderedDict
import json
video = 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': "this is for josn test",
}
}
json_str = json.dumps(test_dict)
with open('test_data.json', 'w') as json_file:
json_file.write(json_str)有縮進:
from collections import defaultdict, OrderedDict
import json
video = 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': "this is for josn test",
}
}
json_str = json.dumps(test_dict, indent=4)
with open('test_data.json', 'w') as json_file:
json_file.write(json_str) 標題名稱:創(chuàng)新互聯(lián)Python教程:python如何將字典內容寫入json文件
分享地址:http://m.fisionsoft.com.cn/article/cochepc.html


咨詢
建站咨詢
