pythonserializationdeserializationpersistence

Storing Python dictionaries


Are there simple ways to store a dictionary (or multiple dictionaries) in, for example, a JSON or pickle file?

For example, if I have some data like:

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

How can I save it in a file, and then later load it back in to the program from the file?


JSON and Pickle can also be used to store more complex structured data. This question may also include answers that are specific to the case of a simple dictionary like the one described. For more general approaches, see How can I write structured data to a file and then read it back into the same structure later?. Note that the technique of converting the data to storable data is called serialization, and re-creating the data structure is called deserialization; storing the data for later use is called persistence.

See also What do files actually contain, and how are they "read"? What is a "format" and why should I worry about them? for some theory about how files work, and why structured data cannot just be written into and read from files directly.


Solution

  • Pickle save:

    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)
    

    See the pickle module documentation for additional information regarding the protocol argument.

    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)