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

Bob Ippolito bob at redivi.com
Sun Feb 29 15:36:42 EST 2004


On 2004-02-29 15:22:32 -0500, ir4u4 at yahoo.com (Equis Uno) said:

> 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?

Getting that data into a dictionary is the easy part..  deciding how 
you want to use it is much harder.

Python 2.3 comes with a module designed specifically to read files that 
look like that, so here's a start:

# none of this code is tested
import csv
myfile = file('myfilename')
myfile.readline() # skip "date,value" line
datevaluemap = dict(csv.reader(myfile))

But your dates and values would end up as strings.. so you might want 
to do something like
datevaluemap = dict([(key, float(value)) for (key, value) in 
csv.reader(myfile)])

Which would get your values in as floats, not strings.  The dates would 
still be strings though, and you might want to use a datetime.date 
object for that.  I don't want to demonstrate how to convert those too, 
since it's longer, uglier, and I don't know strftime format codes off 
the top of my head.. but you can look into datetime.date and 
time.strptime.

-bob




More information about the Python-list mailing list