Python 词典(Dict) 加载与保存示例

yipeiwu_com6年前Python基础

Dict的加载:

import json

def load_dict(filename):
 '''load dict from json file'''
 with open(filename,"r") as json_file:
  dic = json.load(json_file)
 return dic

Dict的保存:

import json
import datetime
import numpy as np

class JsonEncoder(json.JSONEncoder):

 def default(self, obj):
  if isinstance(obj, np.integer):
   return int(obj)
  elif isinstance(obj, np.floating):
   return float(obj)
  elif isinstance(obj, np.ndarray):
   return obj.tolist()
  elif isinstance(obj, datetime):         
   return obj.__str__()
  else:
   return super(MyEncoder, self).default(obj)

def save_dict(filename, dic):
 '''save dict into json file'''
 with open(filename,'w') as json_file:
  json.dump(dic, json_file, ensure_ascii=False, cls=JsonEncoder)

以上这篇Python 词典(Dict) 加载与保存示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Django migrations 默认目录修改的方法教程

如何使用 migrations的使用非常简单: 修改model, 比如增加field, 然后运行 python manager.py makemigrations 你的mmod...

Python 数据可视化pyecharts的使用详解

Python 数据可视化pyecharts的使用详解

什么是pyecharts?   pyecharts 是一个用于生成 Echarts 图表的类库。 echarts是百度开源的一个数据可视化 JS 库,主要用于数据可视化。pyechart...

python numpy 显示图像阵列的实例

python numpy 显示图像阵列的实例

每次要显示图像阵列的时候,使用自带的 matplotlib 或者cv2 都要设置一大堆东西,subplot,fig等等,突然想起 可以利用numpy 的htstack() 和 vstac...

获取python的list中含有重复值的index方法

关于怎么获得,我想其实网上有很多答案。 list.index( )获得值的索引值,但是如果list中含有的值一样,例如含有两个11,22,这样每次获得的都是第一个值的位置。 那么怎么去解...

浅谈Python实现贪心算法与活动安排问题

浅谈Python实现贪心算法与活动安排问题

贪心算法 原理:在对问题求解时,总是做出在当前看来是最好的选择。也就是说,不从整体最优上加以考虑,他所做出的仅是在某种意义上的局部最优解。贪心算法不是对所有问题都能得到整体最优解,但对...