2014-02-10 47 views
0

我试图使用包含Unicode作为字典键的字符串,但我收到此错误:Unicode字符串作为关键的Python字典


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字符的字符串作为关键字还是我们必须执行一些编码操作首先?

+0

这应该有所帮助:http://stackoverflow.com/questions/11694821/dictionary-with-keys-in-unicode – Totem

回答

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是假设一个列表,如果该键不存在。