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

yipeiwu_com5年前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中shape计算矩阵的方法示例

本文实例讲述了Python中shape计算矩阵的方法。分享给大家供大家参考,具体如下: 看到机器学习算法时,注意到了shape计算矩阵的方法接下来就讲讲我的理解吧 >>&...

python之文件读取一行一行的方法

如下所示: f=file('a.txt') for eachline in f: print eachline 以上这篇python之文件读取一行一行的方法就是小编分享给大家的...

解决Atom安装Hydrogen无法运行python3的问题

解决Atom安装Hydrogen无法运行python3的问题

Atom是一款功能强大的跨平台编辑器,插件化的解决方案为atom社区的繁荣奠定了基础。任何人都可以把自己做的组件贡献在github上,并能方便的安装到Atom上使用。 Jupyter N...

解决Python中由于logging模块误用导致的内存泄露

首先介绍下怎么发现的吧, 线上的项目日志是通过 logging 模块打到 syslog 里, 跑了一段时间后发现 syslog 的 UDP 连接超过了 8W, 没错是 8 W. 主要是...

探究Python多进程编程下线程之间变量的共享问题

 1、问题: 群中有同学贴了如下一段代码,问为何 list 最后打印的是空值?   from multiprocessing import Process, M...