SoFunction
Updated on 2025-03-03

Common ways to delete a key in a dictionary in Python

In Python, there are several different methods that can be used to delete a field (key) from the dictionary. Here are some commonly used methods:

usedelStatement:

my_dict = {'a': 1, 'b': 2, 'c': 3}
del my_dict['b']  # Delete the field with the key 'b'print(my_dict)  # Output: {'a': 1, 'c': 3}

usepop()method:

my_dict = {'a': 1, 'b': 2, 'c': 3}
my_dict.pop('b')  # Delete the field with the key 'b' and return the deleted valueprint(my_dict)  # Output: {'a': 1, 'c': 3}

usepop()Method and set the default value in case the key does not exist:

my_dict = {'a': 1, 'b': 2, 'c': 3}
my_dict.pop('b', None)  # If 'b' does not exist, return Noneprint(my_dict)  # Output: {'a': 1, 'c': 3}

usedelStatements andtryandexceptCapture the possibleKeyError

my_dict = {'a': 1, 'b': 2, 'c': 3}
try:
    del my_dict['b']
except KeyError:
    print("Key not found.")
print(my_dict)  # Output: {'a': 1, 'c': 3}

Which method to choose depends on the specific requirements, such as whether you need to deal with the situation where the key does not exist, and whether you need to get the deleted value.

Extension: Methods to delete key values ​​in python dictionary

1. The pop() method deletes the key

Python dictionary is an unordered mapping data type that is stored in the form of key-value pairs, and you can use keys to quickly find the corresponding value. In some cases, we may need to delete a key in the dictionary, and at this time we can use the pop() method provided by the Python dictionary.

The pop() method is used to delete the key specified in the dictionary and return the value corresponding to the key. When using this method, you need to pass in a parameter, that is, the name of the key to be deleted.

# Define a dictionaryfruit_dict = {'apple': 10, 'banana': 20, 'orange': 30}
# Delete the element with the key "apple"res = fruit_dict.pop('apple')
# Output the deleted dictionary and returned valueprint(fruit_dict) # {'banana': 20, 'orange': 30}
print(res) # 10

Note: If the key to be deleted does not exist, pop() will report an error; if the key to be deleted does not exist, you can set the default value to avoid errors.

2. Delete key-value in the dictionary

Delete operations in Python dictionary can also be used with del statements. The del statement can be used to delete key-value pairs in a dictionary.

# Define a dictionaryfruit_dict = {'apple': 10, 'banana': 20, 'orange': 30}
# Delete the element with the key "apple"del fruit_dict['apple']
# Output the deleted dictionaryprint(fruit_dict) # {'banana': 20, 'orange': 30}

3. dict comprehension delete key-value

Another way to delete dictionary keys in Python is to use dictionary derivation formulas. Dictionary derivation is a syntax for creating dictionaries. It can create a new dictionary based on existing dictionaries. The deletion operation can be achieved by excluding the keys that need to be deleted from the original dictionary.

# Define a dictionaryfruit_dict = {'apple': 10, 'banana': 20, 'orange': 30}
# Delete the element with the key "apple"fruit_dict = {k: v for k, v in fruit_dict.items() if k != 'apple'}
# Output the deleted dictionaryprint(fruit_dict) # {'banana': 20, 'orange': 30}

4. Use filter() function to delete key-value

Use the filter() function to filter out unnecessary key-value pairs to achieve the deletion operation.

# Define a dictionaryfruit_dict = {'apple': 10, 'banana': 20, 'orange': 30}
# Delete the element with the key "apple"fruit_dict = dict(filter(lambda x: x[0] != 'apple', fruit_dict.items()))
# Output the deleted dictionaryprint(fruit_dict) # {'banana': 20, 'orange': 30}

5. Use the popitem() method of the dictionary to delete the last element

The popitem() method is used to delete the last key-value pair in the dictionary and return the key-value pair. Prior to Python 3.7, the dictionary was unordered, so popitem() would delete any key-value pair. In Python 3.7 and later, the dictionary is ordered, and popitem() will delete the last key-value pair.

# Define a dictionaryfruit_dict = {'apple': 10, 'banana': 20, 'orange': 30}
# Delete the last elementfruit_dict.popitem()
# Output the deleted dictionary#No one answers the questions encountered during study?  The editor has created a Python learning exchange group: 711312441print(fruit_dict) # {'apple': 10, 'banana': 20}

This is the article about the common methods of deleting a certain key in the dictionary. For more related contents of deleting a dictionary, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!