Remove Items from a Dictionary

You can remove items from a dictionary using methods like pop(), popitem(), or the del statement. These methods allow you to efficiently manage the data within your dictionaries.

Using pop() Method

The pop() method removes the item with the specified key name and returns the value:

Python
person = {
    "name": "John",
    "age": 30,
    "city": "New York",
    "email": "john@example.com"
}

# Remove the "email" key
email = person.pop("email")
print(email)  # Output: john@example.com
print(person)  # Output: {"name": "John", "age": 30, "city": "New York"}

Using del Statement

The del statement removes the item with the specified key name, or deletes the dictionary entirely:

Python
# Remove the "age" key
del person["age"]
print(person)  # Output: {"name": "John", "city": "New York"}

# Delete the entire dictionary
del person
# print(person)  # Raises NameError because "person" no longer exists

Using popitem() Method

The popitem() method removes the last inserted key-value pair (in Python 3.7+):

Python
person = {
    "name": "John",
    "age": 30,
    "city": "New York"
}

# Remove the last inserted item
last_item = person.popitem()
print(last_item)  # Output: ("city", "New York")
print(person)  # Output: {"name": "John", "age": 30}