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?
In order to assign to
allProducts[index][x], first a lookup is done onallProducts[index]to get a dict, then the value you’re assigning is stored at indexxin that dict.However, the first time through the loop,
allProducts[index]doesn’t exist yet. Try this:Since you know all the indices that are supposed to be in
allProductsin advance, you can initialize it before hand like this instead: