search

How to delete items from a dictionary in Python?

In Python, you can delete items from a dictionary using the del keyword or the pop() method. Here are the ways to delete items from a dictionary:

Using the del keyword:

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

# Delete a specific key-value pair
del my_dict['age']

Using the pop() method:

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

# Remove and return the value associated with a specific key
value = my_dict.pop('age')

You can also provide a default value to the pop() method, which will be returned if the key is not found in the dictionary:

my_dict = {'name': 'John', 'city': 'New York'}

# Remove and return the value associated with a specific key
value = my_dict.pop('age', 'Default')

Using the clear() method:

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

# Remove all key-value pairs from the dictionary
my_dict.clear()

Using any of these methods, you can remove specific key-value pairs or clear the entire dictionary.

After deleting items, the dictionary will be modified accordingly. For example:

my_dict = {'name': 'John', 'age': 30, 'city': 'New York'}

del my_dict['age']
# or
my_dict.pop('age')

print(my_dict)  # Output: {'name': 'John', 'city': 'New York'}

It's important to note that if you try to delete a key that doesn't exist in the dictionary, a KeyError will be raised. Using the pop() method with a default value allows you to handle the absence of a key gracefully.

Deleting items from a dictionary allows you to modify and manage the dictionary's contents based on your specific requirements.

Related Questions You Might Be Interested