Home > Article > Backend Development > How to delete elements from python dictionary? How to clear the dictionary?
In today's article, we will learn about deleting dictionary elements in python. In this article, I will explain how to delete dictionary elements in python, and how to delete all elements in the dictionary. Okay, without further ado, let’s get started with the article.
Delete dictionary elements
You can delete a single element or clear the dictionary. Clearing only requires one operation.
Display the del command to delete a dictionary, as shown in the following example:
# !/usr/bin/python # -*- coding: UTF-8 -*- dict = {'Name': 'Zara', 'Age': 7, 'Class': 'First'}; del dict['Name']; # 删除键是'Name'的条目 dict.clear(); # 清空词典所有条目 del dict; # 删除词典 print "dict['Age']: ", dict['Age']; print "dict['School']: ", dict['School'];
But this will cause an exception because the dictionary no longer exists after using del:
dict['Age']: Traceback (most recent call last): File "test.py", line 8, in <module> print "dict['Age']: ", dict['Age']; TypeError: 'type' object is unsubscriptable
Characteristics of dictionary keys
Dictionary values can take any python object without restrictions, either standard objects or user-defined, but keys cannot.
Two important points need to be remembered:
(1). The same key is not allowed to appear twice. If the same key is assigned twice during creation, the latter value will be remembered, as shown in the following example:
# !/usr/bin/python dict = {'Name': 'Zara', 'Age': 7, 'Name': 'Manni'}; print "dict['Name']: ", dict['Name'];
The output result of the above example is:
dict['Name']: Manni
(2). The key must be immutable, Therefore, it can be used as a number, string or tuple, so a list will not work. The following example:
# !/usr/bin/python dict = {['Name']: 'Zara', 'Age': 7}; print "dict['Name']: ", dict['Name'];
The output result of the above example:
Traceback (most recent call last): File "test.py", line 3, in <module> dict = {['Name']: 'Zara', 'Age': 7}; TypeError: list objects are unhashable
The above is all the content of this article , dictionary element deletion in python. I hope what I said and the examples I gave can be helpful to you.
For more related knowledge, please visit the Python tutorial column on the php Chinese website.
The above is the detailed content of How to delete elements from python dictionary? How to clear the dictionary?. For more information, please follow other related articles on the PHP Chinese website!