这是我的代码:
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'
我正在尝试为密钥添加多个值。抛出上面的错误
答案 0 :(得分:3)
结帐setdefault
:
ids.setdefault(key, []).append(value)
它会查看key
是否在ids
中,如果没有,则将其设置为空列表。然后它会返回该列表,以便您在内联调用append
。
文档: http://docs.python.org/2/library/stdtypes.html#dict.setdefault
答案 1 :(得分: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 = {}
一个字典,其默认值将通过调用init参数创建,在这种情况下,调用list()
将生成一个空列表,然后可以将其附加到。
要遍历字典,您可以迭代它items()
for key, val in ids.items():
print(key, val)
答案 2 :(得分: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)
之前的答案是正确的。 defaultdict
和dictionary.setdefault
都是插入空列表的自动方式。