python將字典內(nèi)容寫入json文件的實例代碼
python將字典內(nèi)容寫入json文件的方法:我們可以先使用json.dumps()函數(shù)將字典轉換為字符串;然后再將內(nèi)容寫入json即可。json.dumps()函數(shù)負責對數(shù)據(jù)進行編碼。
字典內(nèi)容寫入json時,需要用json.dumps將字典轉換為字符串,然后再寫入。
json也支持格式,通過參數(shù)indent可以設置縮進,如果不設置的話,則保存下來會是一行。
舉例:
無縮進:
from collections import defaultdict, OrderedDictimport jsonvideo = 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, OrderedDictimport jsonvideo = 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)
以上就是python將字典內(nèi)容寫入json文件的實例代碼的詳細內(nèi)容,更多關于python如何將字典內(nèi)容寫入json文件的資料請關注好吧啦網(wǎng)其它相關文章!
相關文章:
1. python GUI庫圖形界面開發(fā)之PyQt5動態(tài)(可拖動控件大小)布局控件QSplitter詳細使用方法與實例2. CSS3實例分享之多重背景的實現(xiàn)(Multiple backgrounds)3. js開發(fā)中的頁面、屏幕、瀏覽器的位置原理(高度寬度)說明講解(附圖)4. CSS清除浮動方法匯總5. 不要在HTML中濫用div6. XML入門的常見問題(三)7. Python數(shù)據(jù)分析JupyterNotebook3魔法命令詳解及示例8. ASP動態(tài)include文件9. ASP將數(shù)字轉中文數(shù)字(大寫金額)的函數(shù)10. vue跳轉頁面常用的幾種方法匯總
