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

相关文章

Pandas统计重复的列里面的值方法

pandas 代码如下: import pandas as pd import numpy as np salaries = pd.DataFrame({ 'name': ['B...

Python减少循环层次和缩进的技巧分析

Python减少循环层次和缩进的技巧分析

本文实例分析了Python减少循环层次和缩进的技巧。分享给大家供大家参考,具体如下: 我们知道Python中冒号和缩进代表大括号,这样写已经可以节省很多代码行数,但是可以更优化,尽可能减...

Python matplotlib绘图可视化知识点整理(小结)

Python matplotlib绘图可视化知识点整理(小结)

无论你工作在什么项目上,IPython都是值得推荐的。利用ipython --pylab,可以进入PyLab模式,已经导入了matplotlib库与相关软件包(例如Numpy和Scipy...

Python Pandas实现数据分组求平均值并填充nan的示例

Python Pandas实现数据分组求平均值并填充nan的示例

Python实现按某一列关键字分组,并计算各列的平均值,并用该值填充该分类该列的nan值。 DataFrame数据格式 fillna方式实现 groupby方式实现 DataFrame数...

python修改list中所有元素类型的三种方法

修改list中所有元素类型: 方法一: new = list() a = ['1', '2', '3'] for x in a: new.append(int(x)) print(...