python將字典內(nèi)容寫入json文件的實(shí)例代碼
python將字典內(nèi)容寫入json文件的方法:我們可以先使用json.dumps()函數(shù)將字典轉(zhuǎn)換為字符串;然后再將內(nèi)容寫入json即可。json.dumps()函數(shù)負(fù)責(zé)對數(shù)據(jù)進(jìn)行編碼。
字典內(nèi)容寫入json時(shí),需要用json.dumps將字典轉(zhuǎn)換為字符串,然后再寫入。
json也支持格式,通過參數(shù)indent可以設(shè)置縮進(jìn),如果不設(shè)置的話,則保存下來會是一行。
舉例:
無縮進(jìn):
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)
有縮進(jìn):
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)
以上就是python將字典內(nèi)容寫入json文件的實(shí)例代碼的詳細(xì)內(nèi)容,更多關(guān)于python如何將字典內(nèi)容寫入json文件的資料請關(guān)注腳本之家其它相關(guān)文章!
- C#后臺接受前臺JSON字符串裝換成字典集合處理
- 詳談js遍歷集合(Array,Map,Set)
- js實(shí)現(xiàn)復(fù)制功能(多種方法集合)
- jQuery實(shí)現(xiàn)簡單復(fù)制json對象和json對象集合操作示例
- JS中的算法與數(shù)據(jù)結(jié)構(gòu)之集合(Set)實(shí)例詳解
- Redis緩存,泛型集合與json字符串的相互轉(zhuǎn)換實(shí)例
- python字典與json轉(zhuǎn)換的方法總結(jié)
- python 如何將字典寫為json文件
- JavaScript?數(shù)據(jù)結(jié)構(gòu)之字典方法
- JavaScript字典與集合詳解
相關(guān)文章
pytorch如何自定義forward和backward函數(shù)
PyTorch自動(dòng)求導(dǎo)功能強(qiáng)大,但在特定情況下需要用戶自行定義backward函數(shù),通過實(shí)例解釋了保存變量、計(jì)算梯度、鏈?zhǔn)椒▌t等核心概念,并展示了如何通過自定義函數(shù)集成到網(wǎng)絡(luò)中以及如何正確返回梯度,此外,還討論了多輸出情況下的梯度傳遞2024-10-10詳解利用Pytorch實(shí)現(xiàn)ResNet網(wǎng)絡(luò)之評估訓(xùn)練模型
這篇文章主要為大家介紹了利用Pytorch實(shí)現(xiàn)ResNet網(wǎng)絡(luò)之評估訓(xùn)練模型詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-04-04python實(shí)現(xiàn)求解列表中元素的排列和組合問題
本篇文章給大家分享使用python的內(nèi)置模塊實(shí)現(xiàn)求解列表中元素的排列和組合問題,具體實(shí)現(xiàn)代碼大家參考下本文2018-03-03