【问题标题】:KeyError: 'Not Found' when deleting key from a Python DictionaryKeyError:从 Python 字典中删除键时出现“未找到”
【发布时间】:2021-11-22 07:09:11
【问题描述】:

我正在尝试使用 for 循环遍历 Python 字典,然后删除其中一个键/值对,但出现 KeyError: 'Not Found。

这是我的代码。

cars = {
    "brand": "Tesla",
    "model": "Model S Plaid",
    "year":  2021,
    "color": "black"
}

cars_copy = {**cars }
print(cars_copy)

for x in cars_copy.keys():
    result = cars_copy.get("color")
    if result:
        del cars[result]
        print(cars)

这是错误:

德尔汽车[结果] KeyError:'黑色'

【问题讨论】:

  • color 不是cars 中的键,因此get() 调用给出了result"Not Found"。然后您尝试从cars 中删除that,但"Not Found" 也不是键。不清楚您要做什么。
  • 抱歉,刚刚看到我做了更改,但仍然收到错误 del cars[result] KeyError: 'black'
  • 你需要按键删除,而不是按值。因此:del cars['color'].
  • 如果你想从dict中删除一个条目,你应该使用key来删除它。不值。例如。 cars.pop("color", None)
  • 旁注,在循环中删除 dict 项时,您不需要复制整个 dict,只需复制键,例如到一个列表:for x in list(cars.keys()): 并且因为 .keys() 被自动调用:for x in list(cars):

标签: python python-3.x list dictionary


【解决方案1】:

result 在执行result = cars_copy.get("color") 后将有值而不是字典的键。如下更新您的代码。

cars = {
     "brand": "Tesla",
     "model": "Model S Plaid",
     "year":  2021,
     "color": "black"
 }
cars_copy = {**cars }

print(cars_copy)
{'brand': 'Tesla', 'model': 'Model S Plaid', 'year': 2021, 'color': 'black'}

result = cars_copy.get("color", None)
if result:
    del cars['color']
    print(cars)
{'brand': 'Tesla', 'model': 'Model S Plaid', 'year': 2021}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多