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.
This is an old topic, but for completeness, we should include ConfigParser and configparser which are part of the standard library in Python 2 and 3, respectively. This module reads and writes to a config/ini file and (at least in Python 3) behaves in a lot of ways like a dictionary. It has the added benefit that you can store multiple dictionaries into separate sections of your config/ini file and recall them. Sweet!
Python 2.7.x example.
Python 3.X example.
console output
contents of config.ini
If save to a json file, the best and easiest way of doing this is:
Minimal example, writing directly to a file:
or safely opening / closing:
If you want to save it in a string instead of a file:
Pickle save:
See the pickle module documentation for additional information regarding the
protocol
argument.Pickle load:
JSON save:
Supply extra arguments like
sort_keys
orindent
to get a pretty result. The argument sort_keys will sort the keys alphabetically and indent will indent your data structure withindent=N
spaces.JSON load:
If you want an alternative to
pickle
orjson
, you can useklepto
.With
klepto
, if you had usedserialized=True
, the dictionary would have been written tomemo.pkl
as a pickled dictionary instead of with clear text.You can get
klepto
here: https://github.com/uqfoundation/kleptodill
is probably a better choice for pickling thenpickle
itself, asdill
can serialize almost anything in python.klepto
also can usedill
.You can get
dill
here: https://github.com/uqfoundation/dillThe additional mumbo-jumbo on the first few lines are because
klepto
can be configured to store dictionaries to a file, to a directory context, or to a SQL database. The API is the same for whatever you choose as the backend archive. It gives you an "archivable" dictionary with which you can useload
anddump
to interact with the archive.Also see the speeded-up package ujson. https://pypi.python.org/pypi/ujson