I want to save the content of a custom made OrderedDict. (I got the OrderedDict from http://aspn.activestat e.com/ASPN/Python)
The pickle modul seemed to be the solution for the job.
At first I tried to pickle the "nacked" OrderedDict derived from dict, but the pickle routine saves only a empty dict. A secont try to "replace" the __dict__ with the __getstate__ and __setstate__ methods also faild.
How can I save the content (the items of the derived dict and the _keys list) of the OrderedDict via the pickle modul?
here is the code:
The pickle modul seemed to be the solution for the job.
At first I tried to pickle the "nacked" OrderedDict derived from dict, but the pickle routine saves only a empty dict. A secont try to "replace" the __dict__ with the __getstate__ and __setstate__ methods also faild.
How can I save the content (the items of the derived dict and the _keys list) of the OrderedDict via the pickle modul?
here is the code:
Code:
class OrderedDict(dict):
"""This dictionary class extends UserDict to record the order in which items are
added. Calling keys(), values(), items(), etc. will return results in this order."""
def __init__(self, d = None):
self._keys = []
if d == None: d = {}
self.update(d)
def __setitem__(self, key, item):
dict.__setitem__(self,key, item)
if key not in self._keys: self._keys.append(key)
def items(self):
return zip(self._keys, self.values())
def keys(self):
return self._keys[:]
def update(self, d):
dict.update(self, d)
for key in d.keys():
if key not in self._keys: self._keys.append(key)
def __getstate__(self):
"""Return state values to be pickled."""
return (dict(self.items()), self._keys)
def __setstate__(self, state):
"""Restore state from the unpickled state values."""
self.update(state[0])
self._keys = state[1]
if __name__ == "__main__":
import pickle
o = OrderedDict()
o['a'] = [0,1]
o['b'] = [2,3]
p = pickle.dumps(o)
u = pickle.loads(p)
print o # output should be {'b': [2, 3], 'a': [0, 1]}
print u # output should be {'b': [2, 3], 'a': [0, 1]}
# Output:
#{'b': [2, 3], 'a': [0, 1]}
#{}
Comment