1. 程式人生 > >將字典寫入檔案的例子-python

將字典寫入檔案的例子-python

字典內容寫入json時,需要用json.dumps將字典轉換為字串,然後再寫入。

json也支援格式,通過引數indent可以設定縮排,如果不設定的話,則儲存下來會是一行。

from collections import defaultdict
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)#注意這個indent引數 with open('test_data.json', 'w') as json_file: json_file.write(
json_str)