Importing a dicrionary from a file

Skip Montanaro skip at mojam.com
Tue Jan 4 23:33:35 EST 2000


    Keavan> I am a newbie, and i am working on a program that uses a really
    Keavan> big dictionary. i was wondering if i could store the dictionary
    Keavan> in a seperate file, let's say dict.dat.

Sure.  Use a dbm-like object.  Something like

    import anydbm
    db = anydbm.open("dict.dat", "c")	# "c" says "make writable & create 
					# if necessary"
    db["foo"] = "bar"
    ...
    db.close()

should work.  If your definition of big corresponds roughly to mine, you
almost certainly don't want to read the entire thing into memory at once.

Your only restriction is that your keys and values are limited to strings
unless you jump up a level and use shelve.  The lib doc for the shelve
module has a simple example:

    http://www.python.org/doc/lib/module-shelve.html

Cheers,

Skip Montanaro | http://www.mojam.com/
skip at mojam.com | http://www.musi-cal.com/
847-971-7098   | Python: Programming the way Guido indented...




More information about the Python-list mailing list