Best way to store a large python dictionary in a file

前端 未结 2 450
无人共我
无人共我 2021-01-15 03:18

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 bes

相关标签:
2条回答
  • 2021-01-15 03:39

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

    0 讨论(0)
  • 2021-01-15 04:01

    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
    
    0 讨论(0)
提交回复
热议问题