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设计】。

相关文章

Python编程判断这天是这一年第几天的方法示例

Python编程判断这天是这一年第几天的方法示例

本文实例讲述了Python编程判断这天是这一年第几天的方法。分享给大家供大家参考,具体如下: 题目:输入某年某月某日,判断这一天是这一年的第几天? 实现代码: year=int(in...

python在新的图片窗口显示图片(图像)的方法

python在新的图片窗口显示图片(图像)的方法

使用python画图,发现生成的图片在console里。不仅感觉很别扭,很多功能也没法实现(比如希望在一幅图里画两条曲线)。 想像matlab一样单独地生成一个图片窗口,然后我在网上找了...

Python使用urllib2模块实现断点续传下载的方法

本文实例讲述了Python使用urllib2模块实现断点续传下载的方法。分享给大家供大家参考。具体分析如下: 在使用HTTP协议进行下载的时候只需要在头上设置一下Range的范围就可以进...

安装Python的web.py框架并从hello world开始编程

最近有一个小的web项目,想用喜爱都python,但是想到之前接触过都django我感觉一阵不寒而栗,为什么?Django的配置太过复杂,而且小项目不太适合MVC的开发模式,所以...

Python中functools模块的常用函数解析

1.partial 首先是partial函数,它可以重新绑定函数的可选参数,生成一个callable的partial对象: >>> int('10') # 实际上等...