In this article, we'll look at Python's Delete dictionary elements, which I'll explain in this article about how to remove the dictionary elements from Python, and how to delete all the elements in the dictionary. Well, don't say much, let's get into the article.
Delete a dictionary element
The ability to delete a single element also clears the dictionary , emptying only one operation.
Show Delete a dictionary with the Del command, as in the following example:
#!/usr/bin/python#-*-Coding:utf-8-*-dict = {' name ': ' Zara ', ' age ': 7, ' Class ': ' First ';d el dict[' name ']; # Delete key is ' Name ' entry dict.clear (); # Empty dictionary all Entries del dict; # Delete the dictionary print "dict[' age ']:", dict[' age '];p rint "dict[' School ']:", dict[' School '];
However, this throws an exception because the dictionary no longer exists after Del:
dict[' age ']:traceback (most recent): File "test.py", line 8, in <module> print "dict[' age ']:", di Ct[' age ']; TypeError: ' Type ' object is unsubscriptable
Properties of Dictionary Keys
A dictionary value can take any Python object without restriction, either as a standard object or as a user-defined one, but not a key.
Two important points to keep in mind:
(1). The same key is not allowed to appear two times. When created, if the same key is assigned a value of two times, the latter value is remembered, as in the following example:
#!/usr/bin/pythondict = {' name ': ' Zara ', ' age ': 7, ' name ': ' Manni '};p rint ' dict[' name ']: ", dict[' name '];
The result of the above example output:
dict[' Name ']: Manni
(2). The key must be immutable, so it can be used as a number, a string, or a tuple, so a list is not possible, as in the following example:
#!/usr/bin/pythondict = {[' name ']: ' Zara ', ' Age ': 7};p rint ' dict[' name ']: ", dict[' name '];
The result of the above example output:
Traceback (most recent): File "test.py", line 3, <module> dict = {[' Name ']: ' Zara ', ' age ': 7};t Ypeerror:list Objects is unhashable