Writing dictionary to file

Hans-Joachim Widmaier hjwidmai at foxboro.com
Fri Sep 8 09:34:25 CEST 2000


Martijn Faassen:
> 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

This of course only works if your strings contain no whitespace, which is a
serious limitation. If your keys are guaranteed to contain no whitespace and
the values do not contain newlines (this is rather often the case), this
approach works with a small modification in read_dictionary():

Instead of
        key, value = string.split(line)
use
        key, value = string.split(line, 1)

I usually seperate the fields with a character that I knew never appeared
in the strings, like a center dot (which is IMHO also visually pleasing when
you look at the file). Newlines are still no go.

--
Hans-Joachim Widmaier




More information about the Python-list mailing list