python:Unicode相等比较无法将两个参数都转换为Unicode

时间:2017-03-20 08:56:57

标签: python python-2.7 unicode

我有一个dict,想要搜索一下。

test = dict({u'K\xfcndigung' : 123})
tmpKey = str('K\xfcndigung')
print(test[tmpKey])

结果是:

UnicodeWarning: Unicode equal comparison failed to convert both 
arguments to Unicode - interpreting them as being unequal

1 个答案:

答案 0 :(得分:0)

您似乎正在使用Python2,:

>>> test[tmpKey]

Warning (from warnings module):
  File "__main__", line 1
UnicodeWarning: Unicode equal comparison failed to convert both arguments to Unicode - interpreting them as being unequal

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    test[tmpKey]
KeyError: 'K\xfcndigung'

在Python2中,str不是unicode而不是Python3,因此将tmpKey改为unicode对象:

>>> tmpKey = u'K\xfcndigung'
>>> #        ^
>>> 
>>> test[tmpKey]
123