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

ReferenceStackOverFlow

save it as CSV:

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

Then reading it would be:

1
2
3
4
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):

1
2
3
4
import json
dict = {"hello": "world"}
json.dumps(dict)
'{"hello": "world"}'

0%