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?
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With