2014-01-15 64 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都是插入空列表的自动方式。