在Python构建多维字典时出现KeyError

5 投票
5 回答
7355 浏览
提问于 2025-04-16 11:24

我正在尝试创建一个有两个键的字典,但在给字典赋值时遇到了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转换成字典)或者我从亚马逊得到的结果上,因为当我使用'allProducts[x]'或'allProducts[index]'时,构建字典没有问题,但同时使用这两个键时就出错了。

我到底漏掉了什么呢?

5 个回答

1

你可以使用字典的 setdefault 方法。

for x in range(10):
        allProducts.setdefault(index, {})[x] = ...
3

如果你在使用Python 2.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 {}
7

为了给 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

撰写回答