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中super关键字用法实例分析

本文实例讲述了Python中super关键字用法。分享给大家供大家参考。具体分析如下: 在Python类的方法(method)中,要调用父类的某个方法,在Python 2.2以前,通常的...

python实现贪吃蛇小游戏

python实现贪吃蛇小游戏

关于编写游戏,是博主非常向往的东西(博主喜爱游戏),编写游戏得一步一步的走!今天我简单的编写一下非常经典的游戏贪吃蛇!!!! 效果图: 首先引入pygame模块 pip instal...

python3.6使用tkinter实现弹跳小球游戏

本文实例为大家分享了python3.6实现弹跳小球游戏的具体代码,供大家参考,具体内容如下 import random import time from tkinter import...

基于python实现微信模板消息

我的风格,废话不多说了,直接给大家贴代码了,并在一些难点上给大家附了注释,具体代码如下所示: #!/usr/bin/env python #-*- coding:utf-8 -*-...

python对html代码进行escape编码的方法

本文实例讲述了python对html代码进行escape编码的方法。分享给大家供大家参考。具体分析如下: python包含一个cgi模块,该模块有一个escape函数可以用来对html代...