Home > Article > Backend Development > How to remove key from dictionary in Python
Like other Python built-in data types, the dictionary dict also has some practical operation methods. What we are talking about here are the dictionary deletion methods: clear(), pop() and popitem(). These three methods have different functions, operation methods and return values. Next, let’s check out the specific usage of these dictionary-specific methods.
Dictionary clear() method
The clear() method is used to clear all data in the dictionary. Because it is an in-situ operation, it returns None (also understandable There is no return value)
The pop() method of the dictionary
Removes the dictionary data. The function of the pop() method is: Deletes the value corresponding to the given key, returns the value and removes it from the dictionary. Note that the dictionary pop() method works completely differently from the list pop() method.
The popitem() method of the dictionary
The function of the dictionary popitem() method is to randomly return and delete a pair in the dictionary Keys and values (items). Why is it deleted randomly? Because dictionaries are unordered, there is no so-called "last item" or other order. If you encounter work that requires deleting items one by one while working, it is very efficient to use the popitem() method.
The above is the detailed content of How to remove key from dictionary in Python. For more information, please follow other related articles on the PHP Chinese website!