Save a dictionary to a file (alternative to pickle) in Python?
Sure, save it as CSV:
import csvw = csv.writer(open("output.csv", "w"))for key, val in dict.items(): w.writerow([key, val])
Then reading it would be:
import csvdict = {}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"}'
The most common serialization format for this nowadays is JSON, which is universally supported and represents simple data structures like dictionaries very clearly.
>>> members = {'Starspy' : 'SHSN4N', 'Test' : 'Test1'}>>> json.dumps(members)'{"Test": "Test1", "Starspy": "SHSN4N"}'>>> json.loads(json.dumps(members)){u'Test': u'Test1', u'Starspy': u'SHSN4N'}