2014-01-15 222 views
1

這裏是我的代碼:添加多個值字典

for response in responses["result"]: 
    ids = {} 
    key = response['_id'].encode('ascii') 
    print key 
    for value in response['docs']: 
     ids[key].append(value) 

回溯:

File "people.py", line 47, in <module> 
    ids[key].append(value) 
    KeyError: 'deanna' 

我想多添加值的關鍵。拋出像上面

回答

3

退房setdefault錯誤:

ids.setdefault(key, []).append(value) 

看起來,看看是否keyids,如果不是,那將是一個空列表。然後它將返回該列表,以便內聯調用append

文檔: http://docs.python.org/2/library/stdtypes.html#dict.setdefault

+0

如何遍歷這個字典,只是爲了檢查它是否正確地附加了一切? – blackmamba

+1

這完全是一個完全不同的問題,但是你可以在for循環中遍歷它,比如'for key,value in ids.items():' – mhlester

1

如果我正確地讀這你的意圖是映射到其文檔的響應的_id。在這種情況下,你可以打倒你擁有了一切之上的dict comprehension

ids = {response['_id'].encode('ascii'): response['docs'] 
     for response in responses['result']} 

這還假定你的意思是有id = {}外的最外層循環,但我看不到任何其他合理的解釋。


如果以上是不正確的,

您可以使用collections.defaultdict

import collections # at top level 

#then in your loop: 

ids = collections.defaultdict(list) #instead of ids = {} 

字典,其默認值將通過調用初始化參數,在這種情況下調用list()會產生創建一個可以追加到的空白列表。

要遍歷您可以遍歷它的items()

for key, val in ids.items(): 
    print(key, val) 
0

你得到一個KeyError異常的原因字典是這樣的:在第一次迭代的for循環,你看看在一個空的字典的關鍵。沒有這樣的密鑰,因此KeyError。

如果您首先將一個空列表插入字典下適當的密鑰,則您提供的代碼將起作用。然後將值附加到列表中。像這樣:

for response in responses["result"]: 
ids = {} 
key = response['_id'].encode('ascii') 
print key 
if key not in ids: ## <-- if we haven't seen key yet 
    ids[key] = []  ## <-- insert an empty list into the dictionary 
for value in response['docs']: 
    ids[key].append(value) 

以前的答案是正確的。 defaultdictdictionary.setdefault都是插入空列表的自動方式。