Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KeyError while building multidimensional dictionary in Python

I am trying to build a dictionary with two keys but am getting a KeyError when assigning items. I don't get the error when using each of the keys separately, and the syntax seems pretty straightforward so I'm stumped.

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'] 
                                }

I don't believe the issue lies with feedparser (which converts xml to dict) or with the results I'm getting from amazon, as I have no issues building a dict when either using 'allProducts[x]' or 'allProducts[index]', but not both.

What am I missing?

like image 765
kasceled Avatar asked Feb 07 '11 21:02

kasceled


People also ask

How do I fix KeyError in Python?

How to Fix KeyError in Python. To avoid the KeyError in Python, keys in a dictionary should be checked before using them to retrieve items. This will help ensure that the key exists in the dictionary and is only used if it does, thereby avoiding the KeyError . This can be done using the in keyword.

How do you avoid KeyError in the dictionary?

Avoiding KeyError when accessing Dictionary Key We can avoid KeyError by using get() function to access the key value. If the key is missing, None is returned. We can also specify a default value to return when the key is missing.

What is KeyError in Python dictionary?

A Python KeyError exception is what is raised when you try to access a key that isn't in a dictionary ( dict ). Python's official documentation says that the KeyError is raised when a mapping key is accessed and isn't found in the mapping.

How do you access a multi level dictionary in Python?

Access Nested Dictionary Items You can access individual items in a nested dictionary by specifying key in multiple square brackets. If you refer to a key that is not in the nested dictionary, an exception is raised. To avoid such exception, you can use the special dictionary get() method.


1 Answers

In order to assign to allProducts[index][x], first a lookup is done on allProducts[index] to get a dict, then the value you're assigning is stored at index x in that dict.

However, the first time through the loop, allProducts[index] doesn't exist yet. Try this:

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

Since you know all the indices that are supposed to be in allProducts in advance, you can initialize it before hand like this instead:

map(lambda i: allProducts[i] = {  }, searchIndices)
for index in searchIndices:
    # ... rest of loop does not need to be modified
like image 91
Cameron Avatar answered Oct 16 '22 08:10

Cameron