【问题标题】:KeyError when using non-ASCII characters as keys in a python dictionary使用非 ASCII 字符作为 python 字典中的键时出现 KeyError
【发布时间】:2017-02-17 12:19:27
【问题描述】:

我有这个功能:

#!/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(最近一次调用最后一次):文件“filt.py”,第 11 行,在 print filt("árvore") 文件“filt.py”,第 8 行,在 filt new = new + dic[l] KeyError: '\xc3'

怎么了?

【问题讨论】:

  • 对于 unicode 字符串,字符串前面需要"u":例如:u'á',或new = u''。
  • 你用的是哪个版本的python?在 python 3 上,它通过将 dic[l] 更改为 dic.get(l,l) 来流畅地工作
  • 好的,你的 print 调用很明显它是 py2。鑫给你答案

标签: python keyerror


【解决方案1】:

您应该将 word 作为 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 为不是字典键的项目返回原始对象。

【讨论】:

    【解决方案2】:

    在 中编码可能很麻烦。只要涉及任何非 ascii 字符,您就应该使用 unicode 字符串:

    def filt(word):
        dic = dict(zip(u'áéíóú', u'aeiou'))
        return u''.join(dic.get(l, l) for l in word)
    
    > filt(u'árvore')
    'arvore'
    

    使用dict.get(key, default) 可以避免所有不在dic 中的字符出现键错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      相关资源
      最近更新 更多