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开发之settings.py中变量的全局引用详解

django开发之settings.py中变量的全局引用详解

本文主要介绍的是django中settings.py中变量的全局引用的相关资料,下面话不多说,来看看详细的介绍吧。 前言 在settings.py中添加自定义变量,可以通过setting...

Python实现截屏的函数

本文实例讲述了Python实现截屏的函数。分享给大家供大家参考。具体如下: 1.可指定保存目录. 2.截屏图片名字以时间为文件名 3.截屏图片存为JPG格式图片,比BMP小多的,一个10...

Python中规范定义命名空间的一些建议

API的设计是一个艺术活。往往需要其简单、易懂、整洁、不累赘。 很多时候,我们在底层封装一个方法给高层用,而其它的方法只是为了辅助这个方法的。 也就是说我们只需要暴露这个方法就行,不用关...

pygame学习笔记(3):运动速率、时间、事件、文字

pygame学习笔记(3):运动速率、时间、事件、文字

1、运动速率 上节中,实现了一辆汽车在马路上由下到上行驶,并使用了pygame.time.delay(200)来进行时间延迟。看了很多参考材料,基本每个材料都会谈到不同配置机器下运动速率...

python学习入门细节知识点

python入门细节 相除后的类型 type(2/2) float type(2//2) int 双斜杠是整除,出来的类型是int。单斜杠的出来的是float类型。 进制表示和转换...