Unicode字符串作为python字典的关键

时间:2014-02-10 00:19:53

标签: python unicode python-2.x

我正在尝试使用包含unicode的字符串作为字典键,但我收到此错误:


print title

1 - Le chant du départ (Gallo, Max)

print repr(title)

'1 - Le chant du d\xc3\xa9part (Gallo, Max)'

d[title].append([infos,note])

KeyError: '1 - Le chant du d\xc3\xa9part (Gallo, Max)'

我们可以使用包含unicode字符的字符串作为键,还是先做一些编码?

1 个答案:

答案 0 :(得分:3)

您收到的错误是KeyError,表示您的字典中没有该密钥(https://wiki.python.org/moin/KeyError)。当你写

d[title].append([infos,note])

解释器正在寻找您的标题词典中的现有密钥。相反,你应该这样做:

if title in d:
    d[title].append([infos, note])
else:
    d[title] = [infos, note]

首先检查字典中是否存在密钥。如果是这样,这意味着列表已经存在,因此它会对这些值进行处理。如果没有,它会创建一个包含这些值的新列表。

一旦掌握了这一点,您可以查看collections模块以获取默认字典(http://docs.python.org/2/library/collections.html)。然后你可以做类似的事情:

from collections import defaultdict
d = defaultdict(list)
...
d[title].append([infos, note])

现在你不会得到KeyError,因为如果密钥不存在,defaultdict会假设一个列表。