The shelve module, as suggested by jabaldonedo, is a drop-in replacement for dictionaries. However, when your values are all strings, even shelve
is overkill; you can just use dbm.
Either way, you only need to change one line:
d = {} # in-memory, non-persistent dict
d = shelve.open('passwd.db', 'c') # persistent dict that can store anything
d = dbm.open('passwd.db', 'c') # persistent dict that only stores strings
The advantage of dbm is that you can use other tools to read (and edit) the database. For example, if you do this:
d['abc'] = 'def'
With dbm
, the database will hold the string 'def'
. With shelve
, it will hold something like '\x80\x03X\x03\x00\x00\x00defq\x00.'
.