Fil*_*son 1 python unicode dictionary utf-8 python-unicode
我有一个字典,其中包含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'
Run Code Online (Sandbox Code Playgroud)
看起来它们的编码方式不同,不知何故.从实验开始,似乎字典中的关键字被编码为八进制字节(?)http://www.ltg.ed.ac.uk/~richard/utf-8.cgi?input=xc3+xa5&mode=obytes,同时我尝试访问该值的密钥编码为十六进制(?)http://www.ltg.ed.ac.uk/~richard/utf-8.cgi?input=xe5&mode=hex.
字典中的键是从Web源获取的,所以我猜想有些东西在路上搞砸了.
你test
是一个字符串,key
而是一个unicode字符串.看到u
它的前面?
你应该使用Python 3,其中所有字符串都是unicode字符串,或者在字典中查找之前确保将test转换为unicode.
归档时间: |
|
查看次数: |
3265 次 |
最近记录: |