Storing Python dictionaries
我习惯使用.csv文件将数据输入和输出Python,但是存在明显的挑战。 有关在json或pck文件中存储字典(或字典集)的简单方法的任何建议吗? 例如:
1 2 3 | data = {} data ['key1'] ="keyinfo" data ['key2'] ="keyinfo2" |
我想知道如何保存它,然后如何加载它。
泡菜保存:
1 2 3 4 5 6 7 | try: import cPickle as pickle except ImportError: # python 3.x import pickle with open('data.p', 'wb') as fp: pickle.dump(data, fp, protocol=pickle.HIGHEST_PROTOCOL) |
有关
泡菜负荷:
1 2 | with open('data.p', 'rb') as fp: data = pickle.load(fp) |
JSON保存:
1 2 3 4 | import json with open('data.json', 'w') as fp: json.dump(data, fp) |
提供额外的参数,如
1 | json.dump(data, fp, sort_keys=True, indent=4) |
JSON加载:
1 2 | with open('data.json', 'r') as fp: data = json.load(fp) |
最小的例子,直接写入文件:
1 2 3 | import json json.dump(data, open(filename, 'wb')) data = json.load(open(filename)) |
或安全地开/关:
1 2 3 4 5 | import json with open(filename, 'wb') as outfile: json.dump(data, outfile) with open(filename) as infile: data = json.load(infile) |
如果要将其保存在字符串而不是文件中:
1 2 3 | import json json_str = json.dumps(data) data = json.loads(json_str) |
另请参阅加速包ujson。
https://pypi.python.org/pypi/ujson
1 2 3 | import ujson with open('data.json', 'wb') as fp: ujson.dump(data, fp) |
如果您在序列化之后但不需要其他程序中的数据,我强烈推荐使用
1 2 3 4 5 6 7 8 9 10 | myData = shelve.open('/path/to/file') # check for values. keyVar in myData # set values myData[anotherKey] = someValue # save the data for future use. myData.close() |
要写入文件:
1 2 | import json myfile.write(json.dumps(mydict)) |
要从文件中读取:
1 2 | import json mydict = json.loads(myfile.read()) |
如果您想要替代
1 2 3 4 5 6 7 8 9 10 11 12 13 | >>> init = {'y': 2, 'x': 1, 'z': 3} >>> import klepto >>> cache = klepto.archives.file_archive('memo', init, serialized=False) >>> cache {'y': 2, 'x': 1, 'z': 3} >>> >>> # dump dictionary to the file 'memo.py' >>> cache.dump() >>> >>> # import from 'memo.py' >>> from memo import memo >>> print memo {'y': 2, 'x': 1, 'z': 3} |
使用
你可以在这里获得
你可以在这里获得
前几行中额外的mumbo-jumbo是因为
这是一个古老的主题,但为了完整起见,我们应该包括ConfigParser和configparser,它们分别是Python 2和3中标准库的一部分。该模块读取和写入config / ini文件,并且(至少在Python 3中)的行为方式很多,如字典。它还有一个额外的好处,你可以将多个词典存储到config / ini文件的不同部分并调用它们。甜!
Python 2.7.x示例。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 | import ConfigParser config = ConfigParser.ConfigParser() dict1 = {'key1':'keyinfo', 'key2':'keyinfo2'} dict2 = {'k1':'hot', 'k2':'cross', 'k3':'buns'} dict3 = {'x':1, 'y':2, 'z':3} # make each dictionary a separate section in config config.add_section('dict1') for key in dict1.keys(): config.set('dict1', key, dict1[key]) config.add_section('dict2') for key in dict2.keys(): config.set('dict2', key, dict2[key]) config.add_section('dict3') for key in dict3.keys(): config.set('dict3', key, dict3[key]) # save config to file f = open('config.ini', 'w') config.write(f) f.close() # read config from file config2 = ConfigParser.ConfigParser() config2.read('config.ini') dictA = {} for item in config2.items('dict1'): dictA[item[0]] = item[1] dictB = {} for item in config2.items('dict2'): dictB[item[0]] = item[1] dictC = {} for item in config2.items('dict3'): dictC[item[0]] = item[1] print(dictA) print(dictB) print(dictC) |
Python 3.X示例。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | import configparser config = configparser.ConfigParser() dict1 = {'key1':'keyinfo', 'key2':'keyinfo2'} dict2 = {'k1':'hot', 'k2':'cross', 'k3':'buns'} dict3 = {'x':1, 'y':2, 'z':3} # make each dictionary a separate section in config config['dict1'] = dict1 config['dict2'] = dict2 config['dict3'] = dict3 # save config to file f = open('config.ini', 'w') config.write(f) f.close() # read config from file config2 = configparser.ConfigParser() config2.read('config.ini') # ConfigParser objects are a lot like dictionaries, but if you really # want a dictionary you can ask it to convert a section to a dictionary dictA = dict(config2['dict1'] ) dictB = dict(config2['dict2'] ) dictC = dict(config2['dict3']) print(dictA) print(dictB) print(dictC) |
控制台输出
1 2 3 | {'key2': 'keyinfo2', 'key1': 'keyinfo'} {'k1': 'hot', 'k2': 'cross', 'k3': 'buns'} {'z': '3', 'y': '2', 'x': '1'} |
config.ini的内容
1 2 3 4 5 6 7 8 9 10 11 12 13 | [dict1] key2 = keyinfo2 key1 = keyinfo [dict2] k1 = hot k2 = cross k3 = buns [dict3] z = 3 y = 2 x = 1 |
如果保存到json文件,最好和最简单的方法是:
1 2 3 | import json with open("file.json","wb") as f: f.write(json.dumps(dict).encode("utf-8")) |