在Python中构建多维字典时的KeyError

kas*_*led 4 python dictionary multidimensional-array

我正在尝试使用两个键构建一个字典,但在分配项目时遇到了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'] 
                                }
Run Code Online (Sandbox Code Playgroud)

我不相信问题在于feedparser(将xml转换为dict)或者我从亚马逊获得的结果,因为当使用'allProducts [x]'或'allProducts [index]时我没有问题构建dict ]',但不是两个.

我错过了什么?

Cam*_*ron 6

为了分配allProducts[index][x],首先执行查找allProducts[index]以获取dict,然后将要分配的值存储x在该dict 中的索引处.

但是,第一次通过循环,allProducts[index]还不存在.试试这个:

for x in range(10):
    if index not in allProducts:
        allProducts[index] = {  }    # or dict() if you prefer
    allProducts[index][x] = ...
Run Code Online (Sandbox Code Playgroud)

既然您allProducts事先知道了应该进入的所有索引,那么您可以在此之前将其初始化为:

map(lambda i: allProducts[i] = {  }, searchIndices)
for index in searchIndices:
    # ... rest of loop does not need to be modified
Run Code Online (Sandbox Code Playgroud)