2014-02-10 53 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是假設一個列表,如果該鍵不存在。