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

Skip Montanaro skip at
Sun Feb 29 22:30:20 CET 2004

    Equis> Assume I'm given a 100k file full of key-value pairs:

    Equis> date,value
    Equis> 26-Feb-04,36.47
    Equis> 25-Feb-04,36.43
    Equis> 24-Feb-04,36.30
    Equis> 23-Feb-04,37.00
    Equis> 20-Feb-04,37.00
    Equis> 19-Feb-04,37.87

    Equis> What is the best way to copy this data into a Dictionary object?

Maybe overkill, but you have a csv file.  I'd use the csv module (new in

    import csv

    d = {}
    rdr = csv.DictReader(file("source-file"))
    for row in rdr:
        d[row["date"]] = row["value"]


More information about the Python-list mailing list