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

相关文章

Python3.4学习笔记之 idle 清屏扩展插件用法分析

本文实例讲述了Python3.4 idle 清屏扩展插件用法。分享给大家供大家参考,具体如下: python idle 清屏问题的解决,使用python idle都会遇到一个常见而又懊恼...

Python笔记(叁)继续学习

主题: 为什么要有方法呢? 回答居然是:懒惰是一种美德 方法的定义关键词:   def 用callable来判断是否是可调用: 复制代码 代码如下: x = 1 y = math.sqr...

Django时区详解

引言 相信使用Django的各位开发者在存储时间的时候经常会遇到这样子的错误: RuntimeWarning: DateTimeField received a naive date...

Python使用requests发送POST请求实例代码

本文研究的主要是Python使用requests发送POST请求的相关内容,具体介绍如下。 一个http请求包括三个部分,为别为请求行,请求报头,消息主体,类似以下这样: 请求行...

解决Python出现_warn_unsafe_extraction问题的方法

解决Python出现_warn_unsafe_extraction问题的方法

在Python项目中运行出现了“AttributeError: ResourceManager instance has no attribute ‘_warn_unsafe_extra...