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

相关文章

python找出一个列表中相同元素的多个索引实例

定义:X=[1,2,3,1,4] 任务:找出元素为1的索引 Solution: # 如果直接用X.index(1),只能得到0这一个索引,而我们需要所有索引. l = len(X)...

Python八皇后问题解答过程详解

最近看Python看得都不用tab键了,哈哈。今天看了一个经典问题--八皇后问题,说实话,以前学C、C++的时候有这个问题,但是当时不爱学,没搞会,后来算法课上又碰到,只是学会了思想,应...

使用Nginx+uWsgi实现Python的Django框架站点动静分离

由于: Django处理静态文件不太友好; 以后有可能需要处理php或者其他资源的请求; 所以考虑结合nginx,使用nignx做它擅长的路由分发功能;同时做动静分离,即Http请求统一...

Python类和对象的定义与实际应用案例分析

Python类和对象的定义与实际应用案例分析

本文实例讲述了Python类和对象的定义与实际应用。分享给大家供大家参考,具体如下: 1.DVD管理系统 # -*- coding:utf-8 -*- #! python3 clas...

python中map、any、all函数用法分析

本文实例讲述了python中map、any、all函数用法。分享给大家供大家参考。具体分析如下: 最近想学python,就一直比较关注python,昨天在python吧看到有个帖子提问怎...