Delete Elements from a Dictionary by Key in Python

Deleting elements from a dictionary by key allows you to remove specific key-value pairs from the dictionary. In this blog post, we will explore different methods to delete elements from a dictionary by key in Python.

Method 1: Using the del keyword

# Method 1: Using the del keyword
my_dict = {"name": "John", "age": 30, "city": "New York"}
del my_dict["age"]
print("Updated dictionary:", my_dict)

Output:

Updated dictionary: {‘name’: ‘John’, ‘city’: ‘New York’}

Method 2: Using the pop() method

# Method 2: Using the pop() method
my_dict = {"name": "John", "age": 30, "city": "New York"}
my_dict.pop("age")
print("Updated dictionary:", my_dict)

Output:

Updated dictionary: {‘name’: ‘John’, ‘city’: ‘New York’}