我正在尝试用两个键构建一个字典,但是在分配项目时出现KeyError。当分别使用每个键时,我没有收到错误消息,并且语法看起来非常简单,所以我很困惑。

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)或我从亚马逊获得的结果上,因为在使用'allProducts [x]'或'allProducts [index]时我没有问题来构建字典]”,但不能两者都选。

我想念什么?

最佳答案

为了分配给allProducts[index][x],首先对allProducts[index]进行查找以获取字典,然后将您要分配的值存储在该字典中的索引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

10-07 17:50