我想創建一個值爲列表的字典。例如:Python創建列表字典
{
1: ['1'],
2: ['1','2'],
3: ['2']
}
如果我做的:
d = dict()
a = ['1', '2']
for i in a:
for j in range(int(i), int(i) + 2):
d[j].append(i)
我得到一個KeyError異常,因爲d [...]是不是列表。在這種情況下,我可以在賦值a之後添加下面的代碼來初始化字典。
for x in range(1, 4):
d[x] = list()
有沒有更好的方法來做到這一點?可以說,我不知道我需要的密鑰,直到我在第二個for
循環中。例如:
class relation:
scope_list = list()
...
d = dict()
for relation in relation_list:
for scope_item in relation.scope_list:
d[scope_item].append(relation)
另一種做法則與
if d.has_key(scope_item):
d[scope_item].append(relation)
else:
d[scope_item] = [relation,]
什麼是處理這個問題的最好辦法更換
d[scope_item].append(relation)
?理想情況下,追加將「只是工作」。有什麼方法可以表達我想要一個空列表的字典,即使我在第一次創建列表時不知道每個關鍵字?
這可以工作,但通常最好在可用時使用defaultdict。 – 2009-06-06 23:25:49
@David,是的,setdefault並不是最精彩的設計,對不起 - 它幾乎不是最好的選擇。我確實認爲我們(Python提交者)用collections.defaultdict兌現了我們的集體聲望,儘管;-)。 – 2009-06-06 23:46:59