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解析网页源代码中的115网盘链接实例

本文实例讲述了python解析网页源代码中的115网盘链接的方法。分享给大家供大家参考。具体方法分析如下: 其中的1.txt,是网页http://bbs.pediy.com/showth...

分享8个非常流行的 Python 可视化工具包

分享8个非常流行的 Python 可视化工具包

喜欢用 Python 做项目的小伙伴不免会遇到这种情况:做图表时,用哪种好看又实用的可视化工具包呢?之前文章里出现过漂亮的图表时,也总有读者在后台留言问该图表时用什么工具做的。下面,作者...

opencv实现简单人脸识别

opencv实现简单人脸识别

对于opencv 它提供了许多已经练习好的模型可供使用,我们需要通过他们来进行人脸识别 参考了网上许多资料  假设你已经配好了开发环境 ,在我之前的博客中由开发环境的配置。 项...

Django自带日志 settings.py文件配置方法

Django settings.py文件配置部分: # logging配置 log_file = '/home/nagain/learn/log' log_file_path = o...

Python装饰器用法实例总结

本文实例讲述了Python装饰器用法。分享给大家供大家参考,具体如下: 写装饰器 装饰器只不过是一种函数,接收被装饰的可调用对象作为它的唯一参数,然后返回一个可调用对象(就像前面的简单例...