save dictionary for later use?

Hans Nowak zephyrfalcon!NO_SPAM! at gmail.com
Fri May 16 17:23:43 EDT 2008


globalrev wrote:

> pickle.dumps(mg)
> pickle.load(mg)
> 
> 'dict' object has no attribute 'readline'
> dumps load(well i dont know but i get no complaint but running load
> generates that error)

The 'loads' and 'dumps' methods use strings:

 >>> import pickle
 >>> d = {"this": 42, "that": 101, "other": 17}
 >>> s = pickle.dumps(d)
 >>> s
"(dp0\nS'this'\np1\nI42\nsS'other'\np2\nI17\nsS'that'\np3\nI101\ns."
 >>> pickle.loads(s)
{'this': 42, 'other': 17, 'that': 101}

If you want to store to / restore from file, use 'dump' and 'load':

# write to file 'out'...
 >>> f = open("out")
 >>> f = open("out", "wb")
 >>> pickle.dump(d, f)
 >>> f.close()

# restore it later
 >>> g = open("out", "rb")
 >>> e = pickle.load(g)
 >>> g.close()
 >>> e
{'this': 42, 'other': 17, 'that': 101}

Also see http://docs.python.org/lib/pickle-example.html.

Hope this helps!

--Hans



More information about the Python-list mailing list