python - 使用非 ASCII 字符作为 python 字典中的键时出现 KeyError

标签 python keyerror

我有这个功能:

#!/usr/bin/python
# coding=UTF-8

def filt(word):
    dic = {'á':'a','é':'e','í':'i','ó':'o','ú':'u'}
    new = ''
    for l in word:
        new = new + dic[l]
    return new

但是当我为某些字符串(例如“árvore”)调用该函数并运行脚本时,我得到以下结果:

Traceback (most recent call last): File "filt.py", line 11, in print filt("árvore") File "filt.py", line 8, in filt new = new + dic[l] KeyError: '\xc3'

出了什么问题?

最佳答案

您应该将单词作为 unicode 对象传递,因此迭代是在每个 unicode 字符上完成的:

def filt(word):
    dic = {u'á':'a', u'é':'e', u'í':'i', u'ó':'o', u'ú':'u'}
    new = ''
    for l in word:
        new = new + dic.get(l, l)
    return new

print(filt(u"árvore"))
#          ^
# arvore

或者在迭代字符串之前使用word.decode('utf8')

记住也要更新您的字典键,并使用 dict.get 返回不是字典键的项目的原始对象。

关于python - 使用非 ASCII 字符作为 python 字典中的键时出现 KeyError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42297801/

相关文章:

python字典日期时间作为键,keyError

python - PyQt:如何从资源加载 ui 文件?

python - 为什么在我拆分一些 HTML 源代码时会出现 b'(有时是 b' ')[Python]

python - 动态规划难题: Find longest consecutive pairs of 3 (different) pieces

python - 字典中的值的字典 KeyError

python - 为什么 str(KeyError) 添加额外的引号?

python - 在 python 中获取 keyerror

python - DoesNotExist 在/admin/login/站点匹配查询不存在

python - 如何过滤 DataFrame 列表中的数字(n>3)?

python - Pandas 中令人困惑的关键错误