在Python中构建多维字典时出现KeyError
我试图建立一个有两个键的字典,但在分配项时遇到一个键错误。当分别使用每个键时,我没有发现错误,而且语法似乎非常简单,所以我很困惑在Python中构建多维字典时出现KeyError,python,dictionary,multidimensional-array,Python,Dictionary,Multidimensional Array,我试图建立一个有两个键的字典,但在分配项时遇到一个键错误。当分别使用每个键时,我没有发现错误,而且语法似乎非常简单,所以我很困惑 searchIndices = ['Books', 'DVD'] allProducts = {} for index in searchIndices: res = amazon.ItemSearch(Keywords = entity, SearchIndex = index, ResponseGroup = 'Large', ItemPage = 1,
searchIndices = ['Books', 'DVD']
allProducts = {}
for index in searchIndices:
res = amazon.ItemSearch(Keywords = entity, SearchIndex = index, ResponseGroup = 'Large', ItemPage = 1, Sort = "salesrank", Version = '2010-11-01')
products = feedparser.parse(res)
for x in range(10):
allProducts[index][x] = { 'price' : products['entries'][x]['formattedprice'],
'url' : products['entries'][x]['detailpageurl'],
'title' : products['entries'][x]['title'],
'img' : products['entries'][x]['href'],
'rank' : products['entries'][x]['salesrank']
}
我认为问题不在于feedparser(它将xml转换为dict)或我从amazon获得的结果,因为我在使用“allProducts[x]”或“allProducts[index]”构建dict时没有问题,但不是两者都有问题
我遗漏了什么?您需要告诉python它是dict中的dict。它不知道allProducts[index]应该是另一本词典 每当您尝试这样做(或使用defaultdict)时,都需要添加这样的行:
为了分配给
allProducts[index][x]
,首先在allProducts[index]
上进行查找以获得dict,然后分配的值存储在该dict中的索引x
然而,第一次通过循环,allProducts[index]
还不存在。试试这个:
for x in range(10):
if index not in allProducts:
allProducts[index] = { } # or dict() if you prefer
allProducts[index][x] = ...
由于您事先知道allProducts
中应该包含的所有索引,因此您可以将其初始化,如下所示:
map(lambda i: allProducts[i] = { }, searchIndices)
for index in searchIndices:
# ... rest of loop does not need to be modified
你可以使用字典的方法
for x in range(10):
allProducts.setdefault(index, {})[x] = ...
如果您使用的是Python2.5或更高版本,那么这种情况是为
collections.defaultdict
量身定做的
只需更换线路:
allProducts = {}
以下是:
import collections
allProducts = collections.defaultdict(dict)
正在使用的示例如下:
>>> import collections
>>> searchIndices = ['Books', 'DVD']
>>> allProducts = collections.defaultdict(dict)
>>> for idx in searchIndices:
... print idx, allProducts[idx]
...
Books {}
DVD {}
很好,我是Python新手,忘了它不会自动激活。将注册并投票给您,谢谢@tippytop:谢谢,很高兴能提供帮助(你可以点击计票下的复选框,将我的答案标记为已接受)。由于您是Python新手(听起来像个Perl程序员;-),您可能不知道
range
和xrange
之间的区别--range
创建一个所有数字的列表(在内存中),而xrange
创建一个迭代器来逐个生成数字。在这种情况下,range
是可以的,因为您只创建了一个小列表,但是xrange
通常更可取。
import collections
allProducts = collections.defaultdict(dict)
>>> import collections
>>> searchIndices = ['Books', 'DVD']
>>> allProducts = collections.defaultdict(dict)
>>> for idx in searchIndices:
... print idx, allProducts[idx]
...
Books {}
DVD {}