saving dictionaries

Alex Martelli aleaxit at
Fri Dec 22 03:06:46 EST 2000

"QdlatY" <qdlaty at> wrote in message
news:3A4300C7.FA4192AF at
> Hello!
> How to easily save and load contents of dictionaries (2 elements + key)
> to file?

The standard module pickle (and its speedier version cPickle) is a
good solution.  You may also want to look into shelve and anydbm,
which do far more than just 'load and save' but are still connected
to solving persistency issues.

Here's a simple script showing off pickle use: if you run it with
arguments, as in:

    python uno one due two tre three

it will build (and save to file 'dipik.pickled') a dictionary
{'uno': 'one', 'due': 'two', 'tre': 'three'}.

If you then call it without arguments, it will load the dict
from that same file and display it.  It's intended to be a
very simple and purely didactic script, of course -- nothing
complicated or 'advanced' in it!

-- cut
import sys, pickle

filename = 'dipik.pickled'

numargs = len(sys.argv)

if numargs==1:
    # no args: load and display the dictionary
    #     that was last saved to dipik.pickled
    dict = pickle.load(open(filename,"rb"))
    keys = dict.keys()
    for key in keys:
        print "%20s %20s" % (key, dict[key])
    # args: build a dictionary using alternate
    #     args as keys and values, then save it
    dict = {}
    if numargs%2 == 0:
        # odd number of args, ignore last one
        numargs -= 1
    for i in range(1,numargs,2):
        key, value = sys.argv[i:i+2]
        dict[key] = value
    pickle.dump(dict, open(filename,"wb"))
-- end


More information about the Python-list mailing list