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得到一个excel的全部sheet标签值方法

这里需要用到python处理excel很经典的库openpyxl,安装也特别简单。window直接pip install就好了 代码在这里~ wb = openpyxl.load_w...

python脚本实现xls(xlsx)转成csv

# xls_csv 把xls,xlsx格式的文档转换成csv格式 # 使用 python xls2csv.py <xls or xlsx file path> # -*-...

Python的ORM框架SQLObject入门实例

SQLObject和SQLAlchemy都是Python语言下的ORM(对象关系映射)解决方案,其中SQLAlchemy被认为是Python下事实上的ORM标准。当然,两者都很优秀。 一...

pygame实现成语填空游戏

pygame实现成语填空游戏

最近看到很多人玩成语填字游戏,那么先用pygame来做一个吧,花了大半天终于完成了,附下效果图。 偷了下懒程序没有拆分,所有程序写在一个文件里,主要代码如下: # -*- codi...

Python利用WMI实现ping命令的例子

WMI是Windows系统的一大利器,Python的win32api库提供了对WMI的支持,安装win32api即可使用 WMI。 本例通过WMI的WQL实现ping命令。 impo...