2011-02-07 60 views
3

我想用兩個鍵構建一個字典,但在分配項目時出現KeyError。當單獨使用每個鍵時,我不會看到錯誤,而且語法看起來非常簡單,所以我很難過。在Python中構建多維字典時出現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]',但不是兩者。

我錯過了什麼?

回答

5

爲了分配給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 
+0

漂亮,我是新來的Python和忘記它不autovivify。將註冊並upvote你,謝謝! – kasceled 2011-02-07 21:35:15

0

你需要告訴python這是一個字典裏面的字典。它不知道allProducts [index]應該是另一個字典。

您需要添加行這樣每當你想做到這一點(或使用defaultdict):

allProducts = {} 
for index in searchIndices: 
    allProducts[index] = {} 
0
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'] 
           } 
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 {}