Saturday, September 7, 2013

Reading/writing a python dictionary to file

To save time building a large dictionary every time I run my program I googled "saving a python dictionary to file". Of the suggested solutions I liked the option to write to a csv file best. However, the posted code did not work for me because the value in the dictionary was a very big nested list of lists and not a simple string. This was easy to fix by calling eval on the value obtained from the csv reader. Of course I was not the first one to realize this.

Below for completeness my code:

import csv

def saveDict(fn,dict_rap):
    f=open(fn, "wb")
    w = csv.writer(f)
    for key, val in dict_rap.items():
        w.writerow([key, val])
    f.close()
    
def readDict(fn):
    f=open(fn,'rb')
    dict_rap={}
    
    for key, val in csv.reader(f):
        dict_rap[key]=eval(val)
    f.close()
    return(dict_rap)

No comments:

Post a Comment