Writing dictionary to file

Martijn Faassen m.faassen at vet.uu.nl
Thu Sep 7 22:43:10 EDT 2000


Gustaf Liljegren <gustafl at algonet.se> wrote:
> Hi, I'm looking for an elegant way to write a dictionary to a file. I'm not
> sure which format is suitable, but I would like each pair on a row,
> separated by a space, comma, semi-colon or something. Perhaps like this:

> John john at foo.com
> Greg greg at foo.com
> Fred fred at foo.com

If your dictionaries only contain strings:

# untested!

import string

def write_dictionary(f, dict):
    for key, value in dict.items():
        f.write(key)
        f.write(" ")
        f.write(value)
        f.write("\n")

def read_dictionary(f):
    dict = {}
    lines = f.readlines()
    for line in lines:
        line = string.strip(line)
        if not line:
            pass # skip empty lines
        key, value = string.split(line)
        dict[key] = value
    return dict

The more general approach, but you won't get a very readable text file,
is to use the pickle module:

import pickle

pickle.dump(dict, f) # saves dict to file f

# load it again
newdict = pickle.load(f)

But it's very easy, though, and extremely general to boot.

Regards,

Martijn
-- 
History of the 20th Century: WW1, WW2, WW3?
No, WWW -- Could we be going in the right direction?



More information about the Python-list mailing list