Home  >  Article  >  Backend Development  >  How to remove key from dictionary in Python

How to remove key from dictionary in Python

silencement
silencementOriginal
2019-05-23 15:33:314984browse

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)

How to remove key from dictionary in Python

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.

How to remove key from dictionary in Python

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.

How to remove key from dictionary in Python

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn