Reputation:
Hi all so I wrote a function which is something like this
def solve_one_shop(shop, items):
if len(items) == 0:
return [0.0, []]
all_possible = []
first_item = items[0]
print shop['burger']
for (price,combo) in shop[first_item]:
# DO SOMETHING
#
solver(shop_text,['burger'])
The dictionary that Im trying to iterate over is this :
{'1': {'burger': [[4.0, ['burger']]], 'tofu_log': [[8.0, ['tofu_log']]]}, '3': {'chef_salad': [[4.0, ['chef_salad']]], 'steak_salad_sandwich': [[8.0, ['steak_salad_sandwich']]]}, '2': {'burger': [[5.0, ['burger']]], 'tofu_log': [[6.5, ['tofu_log']]]}, '5': {'extreme_fajita': [[4.0, ['extreme_fajita']]], 'fancy_european_water': [[8.0, ['fancy_european_water']]]}, '4': {'wine_spritzer': [[2.5, ['wine_spritzer']]], 'steak_salad_sandwich': [[5.0, ['steak_salad_sandwich']]]}, '6': {'extra_salsa': [[6.0, ['extreme_fajita', 'jalapeno_poppers', 'extra_salsa']]], 'jalapeno_poppers': [[6.0, ['extreme_fajita', 'jalapeno_poppers', 'extra_salsa']]], 'extreme_fajita': [[6.0, ['extreme_fajita', 'jalapeno_poppers', 'extra_salsa']]], 'fancy_european_water': [[5.0, ['fancy_european_water']]]}}
The problem is that the 6th line is giving KeyError ( shop[first_item] ).
[[4.0, ['burger']]]
Traceback (most recent call last):
File "working.py", line 58, in <module>
solver(shop_text,['burger'])
File "working.py", line 44, in solver
(price, solution) = solve_one_shop(shop_info, required_items)
File "working.py", line 29, in solve_one_shop
for (price,combo) in shop.get(first_item):
TypeError: 'NoneType' object is not iterable
To overcome this error I tried hardcoding, so for example if I hardcode the first_item as shop['burger']
(along with single quotes), then the code runs.
But if I write it as shop[burger]
, then it throws the same KeyError: 'burger'
As you can see , print shop['burger']
outputs the availability of the key 'burger'
, but then why the KeyError.
How to fix this?
Upvotes: 0
Views: 13018
Reputation: 73588
You are trying to access a key from the dict
(here shop
), which is not present. Hence the error. Check if that key first_item
is present in your dict
. You would not get this error (updated answer).
...
if first_item in shop:
for (price,combo) in shop[first_item]:
...
or use try: except:
...
try:
for (price,combo) in shop[first_item]:
except KeyError:
print 'ERROR: key not found!'
...
Upvotes: -1
Reputation: 21914
If you want a safer way to access dictionary keys in python I would suggest using the get
method. For instance:
shop.get(first_item, False)
Where the second argument is the default return in case the dictionary does not contain the item you are trying to access.
As Jon pointed out, you can also do something like this:
shop.get(first_item, [])
and iteration will stop if your dictionary doesn't contain that key.
Upvotes: 5