Python中的字典如何删除元素?
使用 del,例如:
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'