大家好,所以我写了一个类似这样的函数
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'])
我试图迭代的字典是这样的:
{'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']]]}}
问题是第 6 行给出了 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
为了克服这个错误,我尝试了硬编码,例如,如果我将 first_item 硬编码为shop['burger']
(以及单引号),那么代码就会运行。
但是如果我把它写成shop[burger]
,那么它会抛出相同的KeyError: 'burger'
如您所见,print shop['burger']
输出密钥的可用性'burger'
,但为什么会出现 KeyError。
如何解决这个问题?