如何从 Python 字典中删除元素

Aliaksei Yursha 2023年1月30日
  1. 删除 Python 字典元素的 del 语句
  2. 删除 Python 字典元素的 dict.pop() 方法
  3. 从 Python 字典中删除多个元素
  4. 性能特点
如何从 Python 字典中删除元素

有时,我们需要删除 Python 字典包含一个或多个键值。你可以通过几种不同的方式来做到这一点。

删除 Python 字典元素的 del 语句

一种方法是使用 Python 的内置 del 语句。

>>> meal = {'fats': 10, 'proteins': 10, 'carbohydrates': 80}
>>> del meal['fats']
>>> meal
{'proteins': 10, 'carbohydrates': 80}

请注意,如果你尝试删除字典中不存在的键,则 Python 运行时将抛出 KeyError

>>> meal = {'fats': 10, 'proteins': 10, 'carbohydrates': 80}
>>> del meal['water']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'water'

删除 Python 字典元素的 dict.pop() 方法

另一种方法是使用 dict.pop() 方法。此方法的好处是,如果字典中不存在所请求的键,则可以指定以默认值来返回。

>>> meal = {'fats': 10, 'proteins': 10, 'carbohydrates': 80}
>>> meal.pop('water', 3000)
3000
>>> meal.pop('fats', 3000)
10
>>> meal
{'proteins': 10, 'carbohydrates': 80} 

请注意,如果你不提供要返回的默认值,并且所请求的键不存在,你还将收到运行时错误,如上面的 del

>>> meal = {'fats': 10, 'proteins': 10, 'carbohydrates': 80}
>>> meal.pop('water')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'water'

从 Python 字典中删除多个元素

如果你需要一次删除字典中的多个元素,Python 3 提供了方便的字典推导式功能,你可以在此处应用字典推导来删除字典中的元素。

>>> meal = {'fats': 10, 'proteins': 10, 'carbohydrates': 80}
>>> [meal.pop(key) for key in ['fats', 'proteins']]
[10, 10]
>>> meal
{'carbohydrates': 80}

请注意,使用上述方法,如果其中给定的键值不在字典中,Python 仍将会报错。为避免此问题,你可以给 dict.pop() 另一个参数作为默认返回值。

>>> meal = {'fats': 10, 'proteins': 10, 'carbohydrates': 80}
>>> [meal.pop(key, None) for key in ['water', 'sugars']]
[None, None]
>>> meal
{'fats': 10, 'proteins': 10, 'carbohydrates': 80}

性能特点

使用 del 语句和 dict.pop() 方法具有不同的性能特征。

>>> from timeit import timeit
>>> timeit("meal = {'fats': 10, 'proteins': 10, 'carbohydrates': 80}; del meal['fats']")
0.12977536499965936
>>> timeit("meal = {'fats': 10, 'proteins': 10, 'carbohydrates': 80}; meal.pop('fats', None)")
0.21620816600079706

如下所示,del 语句的速度几乎快一倍。

但是,dict.pop() 使用默认值会更安全,因为它将帮助你避免运行时错误。

如果你确信关键字必须存在于字典中,请使用前者,否则,请选择后者。

相关文章 - Python Dictionary