【问题标题】:KeyError while building multidimensional dictionary in Python在 Python 中构建多维字典时出现 KeyError
【发布时间】:2011-06-23 00:58:05
【问题描述】:

我正在尝试使用两个键构建字典,但在分配项目时出现 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]' 或 ' 时构建 dict 没有问题allProducts[index]',但不能同时使用。

我错过了什么?

【问题讨论】:

    标签: python dictionary multidimensional-array


    【解决方案1】:

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

    【讨论】:

    • 漂亮,我是 Python 新手,忘记了它不会自动激活。将注册并为您投票,谢谢!
    • @tippytop:谢谢,很高兴能提供帮助(您可以单击投票计数下方的复选标记大纲将我的答案标记为已接受)。由于您是 Python 新手(您听起来像 Perl 程序员 ;-))您可能不知道 rangexrange 之间的区别 -- range 创建一个所有数字的列表(在内存中),而xrange 创建一个迭代器,一个一个地生成数字。在这种情况下,range 是可以的,因为您只是创建了一个小列表,但 xrange 通常更可取。
    【解决方案2】:

    如果您使用的是 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 {}
    

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        【解决方案4】:

        你需要告诉 python 它是一个字典里面的一个字典。它不知道 allProducts[index] 应该是另一个字典。

        每当您尝试这样做(或使用默认字典)时,您都需要添加这样的行:

        allProducts = {}
        for index in searchIndices:
            allProducts[index] = {}
        

        【讨论】:

          【解决方案5】:
          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):
                  if not allProducts.has_key(index):
                      allProducts[index] = {}
                  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'] 
                                          }
          

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 2017-01-06
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2013-04-29
            • 1970-01-01
            相关资源
            最近更新 更多