大家好,所以我写了一个类似这样的函数
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的原因。
如何解决这个问题?
答案 0 :(得分:1)
如果你想在python中使用更安全的方式来访问字典键,我建议使用get
方法。例如:
shop.get(first_item, False)
如果字典不包含您尝试访问的项目,则第二个参数是默认返回。
正如Jon指出的,你也可以这样做:
shop.get(first_item, [])
如果您的字典不包含该密钥,则迭代将停止。
答案 1 :(得分:-1)
您正尝试访问dict
(此处为shop
)的密钥,该密钥不存在。因此错误。检查first_item
中是否存在该密钥dict
。你不会得到这个错误(更新的答案)。
...
if first_item in shop:
for (price,combo) in shop[first_item]:
...
或使用try: except:
...
try:
for (price,combo) in shop[first_item]:
except KeyError:
print 'ERROR: key not found!'
...