Save a dictionary to a file (alternative to pickle) in Python?

Sure, save it as CSV:

import csv
w = csv.writer(open("output.csv", "w"))
for key, val in dict.items():
    w.writerow([key, val])

Then reading it would be:

import csv
dict = {}
for key, val in csv.reader(open("input.csv")):
    dict[key] = val

Another alternative would be json (json for version 2.6+, or install simplejson for 2.5 and below):

>>> import json
>>> dict = {"hello": "world"}
>>> json.dumps(dict)
'{"hello": "world"}'

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)