Best way to store a large python dictionary in a file

匿名 (未验证) 提交于 2019-12-03 02:29:01

问题:

I have a python script (script 1) which generate a large python dictionary. This dictionary has to be read by an another script (script 2). Could any one suggest me the best way to write the python dictionary generated by script 1 and to be read by script 2. In past I have used cPickle to write and read such large dictionaries. Is there a beter way to do this?

回答1:

shelve will give you access to each item separately, instead of requiring you to serialize and deserialize the entire dictionary each time.



回答2:

If you want your dictionary to be readable by different types of scripts (i.e. not just Python), JSON is a good option as well.

It's not as fast as shelve, but it's easy to use and quite readable to the human eye.


import json with open("/tmp/test.json", "w") as out_handle:     json.dump(my_dict, out_handle)  # save dictionary  with open("/tmp/test.json", "r") as in_handle:     my_dict = json.load(in_handle)  # load dictionary 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!