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中set()函数简介及实例解析

set函数也是python内置函数的其中一个,属于比较基础的函数。其具体介绍和使用方法,下面进行介绍。 set() 函数创建一个无序不重复元素集,可进行关系测试,删除重复数据,还可以计算...

Python之使用adb shell命令启动应用的方法详解

一直有一个心愿希望可以用Python做安卓自动化功能测试,在一步步摸索中,之前是用monkeyrunner,但是发现对于控件ID的使用非常具有局限性,尤其是ID的内容不便于区分 具有重复...

学习python中matplotlib绘图设置坐标轴刻度、文本

学习python中matplotlib绘图设置坐标轴刻度、文本

总结matplotlib绘图如何设置坐标轴刻度大小和刻度。 上代码: from pylab import * from matplotlib.ticker import Multi...

Python装饰器的执行过程实例分析

本文实例分析了Python装饰器的执行过程。分享给大家供大家参考,具体如下: 今天看到一句话:装饰器其实就是对闭包的使用,仔细想想,其实就是这回事,今天又看了下闭包,基本上算是弄明白了闭...

numpy中以文本的方式存储以及读取数据方法

Numpy中除了能够把数据以二进制文件的方式保存到文件中以外,还可以选择把数据保存到文本文件中。如果我有磁盘存储的需要,我一般会选择文本的存储,因为后期的处理工具会有更多的选择。 文本存...