[Tutor] Storing Dictionaries Externally

Kent Johnson kent37 at tds.net
Sun Oct 23 03:18:04 CEST 2005


Daniel Watkins wrote:
> Currently, I'm writing a little project which needs to store a
> dictionary in an external file (so it can be accessed by another
> program). However, no matter how much I try, I cannot get Python to
> import the dictionary from the file properly. However, I know the
> problem. Whatever format I put the data in within the file (either as a
> dictionary or a list of tuples to 'dict()') Python reads it as a string,
> rather than a dictionary or list of tuples.

If you are trying to share a dict between two Python programs, the simplest way is to use the pickle module.

To write a dict to a pickle is as simple as
 >>> import pickle
 >>> data = {'a':1, 'b':2}
 >>> f=open('data.txt', 'wb')
 >>> pickle.dump(data, f)
 >>> f.close()

The output is not particularly human-readable; in this case data.txt contains
(dp0
S'a'
p1
I1
sS'b'
p2
I2
s.

but that doesn't really matter; to read it back, use pickle again:
 >>> f=open('data.txt', 'rb')
 >>> newData = pickle.load(f)
 >>> newData
{'a': 1, 'b': 2}
 >>> f.close()

Kent



More information about the Tutor mailing list