Best way to create a Dictionary from file of Key-Value pairs?

Sean Ross sross at connectmail.carleton.ca
Sun Feb 29 15:48:55 EST 2004


"Equis Uno" <ir4u4 at yahoo.com> wrote in message
news:692feddd.0402291222.6f2d619e at posting.google.com...
> Hi,
>
> Assume I'm given a 100k file full of key-value pairs:
>
> date,value
> 26-Feb-04,36.47
> 25-Feb-04,36.43
> 24-Feb-04,36.30
> 23-Feb-04,37.00
> 20-Feb-04,37.00
> 19-Feb-04,37.87
>
> What is the best way to copy this data into a Dictionary object?
>
> -moi

Here's one way:

d = dict([l.strip().split(',') for l in open(fname)])

This opens the file, reads one line at a time, trims the beginning and end
of the line, splits the line at the comma delimiter - your key-value pairs -
and builds a list of these key-value pairs which is then used by dict() to
make a new dictionary. This is not really a robust solution, but you get the
idea. Your solution may require more processing if you want the values to be
floats (for example) or if there might be blank lines or extra white space
in the data, or whatever other issues you may want to guard against. Plus,
you may want to move the open() operation outside of the list comprehension
so you can check/handle possible errors (like file not found, for instance),
as well as close the file, that sort of thing ...

HTH,
Sean





More information about the Python-list mailing list