[Tutor] Writing dictionaries to a file

Kent Johnson kent37 at tds.net
Tue Apr 8 13:42:36 CEST 2008

W W wrote:

> I was toying around with dictionaries/files/etc, and it's possible to
> loop over the dictionary, writing each key/value pair to the file on
> one line with a comma between them

> And if you knew certain values might be ints, you could use
> try: mydict[int(row[0])] = row[1]

This is converting the key, not the value.
> except ValueError: mydict[row[0]] = row[1]

And if the value looks like an int but shouldn't be interpreted as one? 
For example a zip code?

This is getting crazy enough that I have to show how easy it is to do 
with pickle. I used a dict with a mix of types for both keys and values 
to show that they are restored correctly:

To save a dict in a pickle:
In [27]: from pickle import dump, load
In [38]: d = { 'a':1, 'b':'2', ('c', 'd'):(3, 4) }
In [39]: f=open('pickle.dat', 'w')
In [40]: dump(d, f)
In [41]: f.close()

To load the dict back:
In [42]: f=open('pickle.dat')
In [43]: d2=load(f)
In [44]: f.close()
In [45]: d2
Out[45]: {'a': 1, 'b': '2', ('c', 'd'): (3, 4)}

Note that this is the simplest example. There are some performance 
improvements possible - use a binary pickle protocol and cPickle - but 
for most usage I don't think you will notice the difference.


More information about the Tutor mailing list