存储Python字典 [英] Storing Python dictionaries

查看:171
本文介绍了存储Python字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我习惯于使用.csv文件将数据传入和传出Python,但这方面有明显的挑战。任何关于在json或pck文件中存储字典(或一组字典)的简单方法的建议?例如:

  data = {} 
data ['key1'] =keyinfo
data ['key2'] =keyinfo2

我想知道如何保存这个,那么如何加载它。

解决方案

Pickle 保存:

 导入cPickle as pickle 
with open('data.p','wb')as fp:
pickle.dump(data,fp)

Pickle 加载:

  with open('data.p','rb')as fp:
data = pickle.load(fp)






JSON 保存:

  import json 
with open('data.json','w')as fp:
json.dump(data,fp)

提供额外的参数,如 sort_keys indent 以获得一个很好的结果。参数 sort_keys 将按字母顺序对键进行排序,并且缩进将使用 indent = N 空格缩进您的数据结构。 p>

  json.dump(data,fp,sort_keys = True,indent = 4)
/ pre>

JSON 加载:

  with open('data.json','r')as fp:
data = json .load(fp)


I'm used to bringing data in and out of Python using .csv files, but there are obvious challenges to this. Any advice on simple ways to store a dictionary (or sets of dictionaries) in a json or pck file? For example:

data = {}
data ['key1'] = "keyinfo"
data ['key2'] = "keyinfo2"

I would like to know both how to save this, and then how to load it back in.

解决方案

Pickle save:

import cPickle as pickle
with open('data.p', 'wb') as fp:
    pickle.dump(data, fp)

Pickle load:

with open('data.p', 'rb') as fp:
    data = pickle.load(fp)


JSON save:

import json
with open('data.json', 'w') as fp:
    json.dump(data, fp)

Supply extra arguments like sort_keys or indent to get a pretty result. The argument sort_keys will sort the keys alphabetically and indent will indent your data structure with indent=N spaces.

json.dump(data, fp, sort_keys=True, indent=4)

JSON load:

with open('data.json', 'r') as fp:
    data = json.load(fp)

这篇关于存储Python字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆