Python pickle在版本之间转换为unicode

Map*_*sis 1 python unicode pickle

我有一个使用Python 3.2腌制字典的过程.然后我需要使用Python 2.7或2.6来解开这个字典.问题是当在python版本之间进行传输时,我会得到一个充满unicode数据的字典,这会扰乱我试图将其输入的Python API.

在Python 3.2中腌制:

myDict = {'a': 'first', 'b': 'second', 'c': 'third'}
with open(file, 'wb') as f:
    pickle.dump(myDict, f, 2)
Run Code Online (Sandbox Code Playgroud)

在Python 2.6中取消:

with open(file, f) as f:
    myDict = pickle.load(f)
Run Code Online (Sandbox Code Playgroud)

回归:{u'a':你'第一',你'':你'第三',你'':你'第二'}

我怎样才能准确回到我所投入的内容(即不是unicode)?

Ste*_*eef 6

你实际上正好回到了你所放入的内容,因为Python 3 中的字符串 unicode

要获得str,您可以转换字典中的键和值:

strDict = dict((k.encode(), v.encode()) for k, v in myDict.iteritems())
Run Code Online (Sandbox Code Playgroud)