【问题标题】:KeyError iterating through keys in a listKeyError 遍历列表中的键
【发布时间】:2014-03-25 11:31:37
【问题描述】:

大家好,所以我写了一个类似这样的函数

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。

如何解决这个问题?

【问题讨论】:

  • 1) 我没有看到 KeyError,我看到了类型错误。 2) burger'burger' 根本不是一回事。前者查找名为burger 的变量以将其值用作键。第二个是字符串'burger'。 3) TypeError 表明 shop 是空的 (None) 而不是包含 dict

标签: python dictionary keyerror


【解决方案1】:

如果您想要一种更安全的方式来访问 python 中的字典键,我建议使用get 方法。例如:

shop.get(first_item, False)

如果字典不包含您尝试访问的项目,则第二个参数是默认返回。

正如 Jon 指出的,你也可以这样做:

shop.get(first_item, [])

如果您的字典不包含该键,则迭代将停止。

【讨论】:

  • 是的,如果您使用[] 作为默认值(而不是False),那么for 循环将按原样工作,或者实际上是一个无操作...跨度>
  • @JonClements 感谢您的提及,已添加。
  • Slater Ive 编辑了帖子以明确我的要求。请帮助我。再次感谢。
  • @sunita 您正在调用solver,但您的函数被称为solve_one_shop - 确保您的代码在您的问题中是正确的,因为它混淆了您实际尝试运行的内容和您的内容重新运行...
【解决方案2】:

您正在尝试从不存在的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!'
    ...

【讨论】:

  • has_key 已被弃用了 很长时间 时间(并且已在 Python 3 中消失)。请改用if first_item in dict:
  • 或者,更 Python 的方式,只是尝试检索它和 except KeyError,这样你就不会两次散列你的输入。
猜你喜欢
  • 2017-10-19
  • 1970-01-01
  • 2016-09-23
  • 2020-05-01
  • 2021-10-16
  • 2018-10-07
  • 2022-01-04
  • 2016-08-27
  • 2011-09-14
相关资源
最近更新 更多