发布于 4年前

Python中的字典如何删除元素?

使用 del,例如:

In [1]: a = {"hello": "World"}

In [2]: a
Out[2]: {'hello': 'World'}

In [3]: del a["hello"]

In [4]: a
Out[4]: {}
但是注意,如果删除不存在的元素,会报错:

In [5]: del a["this"]
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-5-f4cb891984ed> in <module>
----> 1 del a["this"]

KeyError: 'this'
©2020 edoou.com   京ICP备16001874号-3