在python2中从python3中解开OrderedDict

时间:2015-11-06 14:17:48

标签: python pickle

我正在尝试取消python3中腌制的对象。这适用于python3但不适用于python2。该问题可以复制到pickle协议0.示例代码:

import pickle
import collections

o = collections.OrderedDict([(1,1),(2,2),(3,3),(4,4)])
f = open("test.pkl", "wb")
pickle.dump(o, f, 0)
f.close()

这导致以下pkl文件:

python2:

ccollections
OrderedDict
p0
((lp1
(lp2
I1
aI1
aa(lp3
I2
aI2
aa(lp4
I3
aI3
aa(lp5
I4
aI4
aatp6
Rp7

python3:

cUserString
OrderedDict
p0
(tRp1
L1L
L1L
sL2L
L2L
sL3L
L3L
sL4L
L4L
s.

当我尝试从python2加载python3中创建的pickle文件时,我遇到以下异常:

Python 2.7.6 (default, Jun 22 2015, 17:58:13) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> f = open("test.pkl", "rb")
>>> p = pickle.load(f)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/lib/python2.7/pickle.py", line 1378, in load
    return Unpickler(file).load()
  File "/usr/lib/python2.7/pickle.py", line 858, in load
    dispatch[key](self)
  File "/usr/lib/python2.7/pickle.py", line 1090, in load_global
    klass = self.find_class(module, name)
  File "/usr/lib/python2.7/pickle.py", line 1126, in find_class
    klass = getattr(mod, name)
AttributeError: 'module' object has no attribute 'OrderedDict

然而,将pickle文件中的第一行从UserString更改为集合类可以解决问题。

Python 2.7.6 (default, Jun 22 2015, 17:58:13) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> f = open("test.pkl", "rb")
>>> p = pickle.load(f)
>>> p
OrderedDict([(1L, 1L), (2L, 2L), (3L, 3L), (4L, 4L)])

这是python3中的pickle中的错误吗?

1 个答案:

答案 0 :(得分:1)

确保在Python 2中导入collections。此代码适用于我:

Python 3 - 进行酸洗:

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 - 执行unpickling:

import pickle
import collections

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

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

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