Skip to main content
 首页 » 编程设计

python之UTF-8 字符串作为字典中的键导致 KeyError

2025年05月04日42langtianya

我有一个以 unicode 字符串作为键的字典。当我尝试访问该值时出现键错误,即使字典中键的打印输出与我的键相同:

>>> test = "Byggår" 
>>> key = raw_dict.keys()[7] 
>>> print(test) 
Byggår 
>>> print(key) 
Byggår 
>>> test 
'Bygg\xc3\xa5r' 
>>> key 
u'Bygg\xe5r' 
>>> raw_dict[test] 
Traceback (most recent call last): 
  File "/Applications/PyCharm.app/Contents/helpers/pydev/pydevd_exec.py", line 3, in Exec 
  File "<input>", line 1, in <module> 
KeyError: 'Bygg\xc3\xa5r' 

似乎它们的编码方式不同,不知何故。从实验来看,字典中的键似乎被编码为八进制字节(?)http://www.ltg.ed.ac.uk/~richard/utf-8.cgi?input=xc3+xa5&mode=obytes ,而我尝试访问值的 key 编码为十六进制(?)http://www.ltg.ed.ac.uk/~richard/utf-8.cgi?input=xe5&mode=hex .

字典中的键是从网络资源中获取的,所以我猜有些东西在途中搞砸了。

请您参考如下方法:

您的 test 是一个字符串,而 key 是一个 unicode 字符串。看到它前面的 u 了吗?

您应该使用 Python 3,其中所有字符串都是 unicode 字符串,或者确保在字典中查找之前将 test 转换为 unicode。