Best way to create a Dictionary from file of Key-Value pairs?
bob at redivi.com
Sun Feb 29 21:36:42 CET 2004
On 2004-02-29 15:22:32 -0500, ir4u4 at yahoo.com (Equis Uno) said:
> Assume I'm given a 100k file full of key-value pairs:
> 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
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
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
More information about the Python-list