Skip to main content
 首页 » 编程设计

Python pickle 在版本之间转换为 unicode

2025年05月04日17bhlsheji

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

在 Python 3.2 中 pickle :

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

在 Python 2.6 中解封:

with open(file, f) as f: 
    myDict = pickle.load(f) 

返回:{u'a': u'first', u'c': u'third', u'b': u'second'

我怎样才能准确取回我输入的内容(即不是 unicode)?

请您参考如下方法:

您实际上得到的正是您输入的内容,因为 Python 3 are unicode 中的字符串

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

strDict = dict((k.encode(), v.encode()) for k, v in myDict.iteritems())