且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从python2中的python3解开OrderedDict

更新时间:2021-09-10 04:55:38

确保在Python 2中导入collections.此代码对我有用:

Make sure you import collections in Python 2. This code works for me:

Python 3-进行腌制:

Python 3 - do the pickling:

import pickle
import collections

o = collections.OrderedDict([(1,1),(2,2),(3,3),(4,4)])
with open('/home/bo/Desktop/test.pkl', 'wb') as f:
    pickle.dump(o, f, 2)

Python 2-进行解腌:

Python 2 - do the unpickling:

import pickle
import collections

with open('/home/bo/Desktop/test.pkl', 'rb') as f:
    o = pickle.load(f)

当我这样做时,我可以毫无问题地阅读o:

When I do that I can read o with no issue:

>>> o
0: OrderedDict([(1, 1), (2, 2), (3, 3), (4, 4)])