I have a defaultdict being written to file like this:

writer = csv.writer(open(locationToSaveFile, 'wb+'))    
for k,v in dict.iteritems():
    writer.writerow([k ,v])

I then have this horribly convoluted text to read it back in:

myDict = defaultdict(list) 
with open(fileLocation, 'rb') as test:
    reader = csv.DictReader(test, ['processedText', 'date'])

    for line in reader:

textDict = defaultdict(list) 

for processedText, date in myDict.items():
    actual_list = ast.literal_eval(date[0])
    for a in actual_list:

for processedText, date in textDict.items(): 

Obviously this looks very wasteful (and looks horrible!) but I don't know how else to import the defaultdict.

When opening it with the reader = and for line in reader lines it creates a list within a list. The only way out of this is to use ast to convert it.

Could somebody advise me how to tidy this up?

Note: I'm very unfamiliar with Python


2 Answers 2


csv is meant to store rows of data, not a simple dictionary. You can use json for that:

import json

# writing
json.dump(yourdict, open(filename, 'w'))

# reading
yourdict = json.load(open(filename))
  • \$\begingroup\$ How do I read it back from JSON. I can write it using json.dump(filelocation, defaultdict). But how do I import it again? \$\endgroup\$ Commented Sep 3, 2013 at 16:56
  • \$\begingroup\$ Andrew, use json.load(filelike_object) \$\endgroup\$ Commented Sep 8, 2013 at 12:19

Your dict's values are lists. A possible approach is to expand those lists into csv columns, producing a file where the number of columns varies from row to row:

with open(locationToSaveFile, 'w') as f:
    writer = csv.writer(f)    
    for k,v in mydict.iteritems():
        writer.writerow([k] + v)

with open(locationToSaveFile, 'r') as f:
    reader = csv.reader(f)    
    mydict = collections.defaultdict(list)
    for row in reader:
        mydict[row[0]] = row[1:]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.