Remove Elements from a Dictionary in Python

In Python, dictionaries provide several methods to remove elements based on keys. Let’s explore different methods to remove elements from a dictionary.

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(my_dict)

Output:

{‘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(my_dict)

Output:

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