[Tutor] Writing dictionaries to a file

W W srilyk at gmail.com
Tue Apr 8 12:50:15 CEST 2008

On Mon, Apr 7, 2008 at 2:50 PM, Kent Johnson <kent37 at tds.net> wrote:
> Jerrold Prothero wrote:
>  >
>  > I've been trying to understand how writing a dictionary to a file & reading
>  > it back should work.
>  >
>  > It's been suggested that if I had a clue, I'd use pickle, but since I
>  > started
>  > looking at the csv (comma separated values) module, which also supports
>  > writing dictionaries out to a file, I at least wanted to understand how it's
>  > supposed to work with csv.
>  The csv module writes one dictionary per row of the CSV file. It is
>  intended for storing repeated data, though you could just read and write
>  a single row. When it reads the data back, everything will be returned
>  as a string. This may not be the best fit for your situation.

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

for items in dictionary.items():
    file.write("%s,%s\n" % items)

Then it's simple enough to read the file using csv.reader() (I think
that's the right one)
which turns the values into lists.

So {3:"Hello"} => "3","Hello" => ['3', 'Hello],

if you were to loop over the output (I haven't toyed with this, so I'm
not sure if running csv.reader() on readline(s?) would be faster, or
some sort of loading the lists into some other type of object), you
could easily assign them to a dict:

for row in filedata:
    mydict[row[0]] = row[1]

And if you knew certain values might be ints, you could use

try: mydict[int(row[0])] = row[1]

except ValueError: mydict[row[0]] = row[1]

Hope this helps!

More information about the Tutor mailing list