执行
我正试图使用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)
这是错误:
del cars〔结果〕KeyError:"black">
result = cars_copy.get("color")
后,result
将具有字典的值,而不是关键字。按如下方式更新您的代码。
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}