怎么把python的dict存为json格式文件

  统计/机器学习 Python I/O    浏览次数:7047        分享
0

怎么把一个dict类型的变量存为json格式的文件到本地?

 

猴老大   2018-12-03 10:14



   2个回答 
2

使用dumps将dict转化成json格式写入到json文件中

import json

def dict_to_json():
    dict = {}
    dict['name'] = '123'
    dict['age'] = 10
    dict['sex'] = 'male'
    #转换成json
    j = json.dumps(dict)
    #写到json文件
    fileObject = open('jsonFile.json', 'w')
    fileObject.write(j)
    fileObject.close()

if __name__ == '__main__':
    dict_to_json()


SofaSofa数据科学社区DS面试题库 DS面经

xfang2154   2018-12-04 11:04

谢谢 - 猴老大   2018-12-19 13:20
1


import json
my_dict = {'year': '2018', 'day': '12-04'}
with open('my_dict.json', 'w') as outfile:  
    json.dump(my_dict, outfile)


SofaSofa数据科学社区DS面试题库 DS面经

zl_pku   2018-12-04 14:28

谢谢 - 猴老大   2018-12-19 13:20


  相关讨论

python能不能直接读取word文本,doc或者docx文件?

怎么把statsmodels训练的模型本地保存?

python如何读取元素中含有逗号的csv文件

python怎么读取txt格式的数据文件?

怎么在python中读取mat格式数据文件?

python 读json 错误 ValueError: Unexpected character found when decoding array value (2)

关于如何读取文件效率最高,最节约内存?

怎么把多个csv表格读进python然后合并成一个表格输出为csv?

如何将matplotlib生成的图片存到本地?

pandas读取csv中指定的某些列

  随便看看

随机森林(random forest)和支持向量机(SVM)各有什么优劣

二元分类问题中经常提到的TP,TN,FN,FP都是什么意思?

怎么计算(估计)ROC AUC的置信区间?

凸函数、凸集分别是什么意思?

医学统计里的c-index或者c-statistic是什么意思?