python將字典內容寫入json文件的實例代碼
python將字典內容寫入json文件的方法:我們可以先使用json.dumps()函數將字典轉換為字符串;然后再將內容寫入json即可。json.dumps()函數負責對數據進行編碼。
字典內容寫入json時,需要用json.dumps將字典轉換為字符串,然后再寫入。
json也支持格式,通過參數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將字典內容寫入json文件的實例代碼的詳細內容,更多關于python如何將字典內容寫入json文件的資料請關注好吧啦網其它相關文章!
相關文章:
1. 詳解Android studio 動態fragment的用法2. 基于android studio的layout的xml文件的創建方式3. 編程語言PHP在Web開發領域的優勢在哪?4. 解決Android studio xml界面無法預覽問題5. 什么是python的自省6. Spring Boot和Thymeleaf整合結合JPA實現分頁效果(實例代碼)7. 圖文詳解vue中proto文件的函數調用8. Android如何加載Base64編碼格式圖片9. Springboot Druid 自定義加密數據庫密碼的幾種方案10. Vue封裝一個TodoList的案例與瀏覽器本地緩存的應用實現

網公網安備