How do I store dictionaries in a file and read/write that file? How do I store dictionaries in a file and read/write that file? tkinter tkinter

How do I store dictionaries in a file and read/write that file?


Sound's like you'd need to load the dictionary to memory at init time, and use it like a normal dictionary.

I am assuming your dictionary is a standard python dict of strings, so I recommend using the python json lib.

Easiest way to do this is to export the dictionary as json once to a file using something like:

with open(filename, 'w') as fp:    json.dump(dictionary, fp)

and then change your code to load the dict at init time using:

with open(filename) as fp:    dictionary = json.load(fp)

Alternatively, if your data is more complex than text, you can use python shelve which is a persistent, dictionary-like object to which you can pass any pickle-able object. Note that shelve has its drawbacks so read the attached doc.


sqlitedict is a project providing a persistent dictionary using sqlite in the background. You can use it like a normal dictionary e.g. by assigning arbitrary (picklable) objects to it.

If you access an element from the dictionary, only the value you requested is loaded from disk.