dict.update() / dict.pop() / dict.clear()
Methods for updating and removing entries in a dictionary. They cover merging dictionaries, deleting specific keys, and clearing all entries.
Syntax
# Updates the dictionary with another dictionary or keyword arguments (existing keys are overwritten). dict.update(other_dict_or_keyword_args) # Removes the specified key and returns its value. Returns the default value if the key is not found. dict.pop(key, default) # Removes and returns the last inserted key-value pair (insertion order is guaranteed in Python 3.7+). dict.popitem() # Removes all elements from the dictionary (the dictionary object itself remains). dict.clear() # Removes a specific key-value pair (no return value). del dict[key]
Method List
| Method / Syntax | Description |
|---|---|
| dict.update(other) | Updates the dictionary with the contents of other. Existing keys are overwritten and new keys are added. Returns None. |
| dict.pop(key, default) | Removes the specified key and returns its value. If the key does not exist, returns default. If default is omitted and the key is not found, raises KeyError. |
| dict.popitem() | Removes and returns the last inserted key-value pair as a (key, value) tuple. Raises KeyError if the dictionary is empty. |
| dict.clear() | Removes all elements from the dictionary, leaving it empty. Returns None. |
| del dict[key] | Removes the specified key-value pair. No value is returned. |
Sample Code
# Use update() to merge another dictionary into the current one.
user = {"name": "Alice", "age": 20}
updates = {"age": 21, "city": "Osaka"} # Updates "age" and adds "city".
user.update(updates)
print(user) # {'name': 'Alice', 'age': 21, 'city': 'Osaka'}
# You can also update using keyword arguments.
user.update(job="engineer", email="alice@example.com")
print(user) # "job" and "email" are added.
# Python 3.9+ supports the | operator (merge) and |= operator (update).
dict1 = {"a": 1, "b": 2}
dict2 = {"b": 20, "c": 30}
merged = dict1 | dict2 # Creates a new dictionary (dict1 is unchanged).
print(merged) # {'a': 1, 'b': 20, 'c': 30}
dict1 |= dict2 # Updates dict1 in place.
print(dict1) # {'a': 1, 'b': 20, 'c': 30}
# Use pop() to remove a key and retrieve its value.
profile = {"name": "Bob", "age": 25, "temp_token": "abc123"}
token = profile.pop("temp_token") # Removes the key and gets the value.
print(token) # abc123
print(profile) # {'name': 'Bob', 'age': 25}
# Safely remove a key that may not exist by providing a default value.
removed = profile.pop("phone", None)
print(removed) # None (no error raised)
# Use popitem() to remove and return the last inserted key-value pair.
data = {"x": 1, "y": 2, "z": 3}
last = data.popitem()
print(last) # ('z', 3) (the last inserted item)
print(data) # {'x': 1, 'y': 2}
# Use del to remove a key (no value is returned).
settings = {"theme": "dark", "lang": "en", "debug": True}
del settings["debug"]
print(settings) # {'theme': 'dark', 'lang': 'en'}
# Use clear() to remove all elements.
settings.clear()
print(settings) # {} (empty dictionary)
# Practical example: filter a dictionary to keep only certain keys.
config = {
"host": "localhost",
"port": 5432,
"debug": True,
"password": "secret",
"timeout": 30
}
# Create a safe copy for logging by excluding the password.
safe_config = {k: v for k, v in config.items() if k != "password"}
print(safe_config) # The "password" key is excluded.
Notes
Use update() to merge one dictionary into another. Existing keys are always overwritten, so it cannot be used when you want to preserve existing values. If you want to add only new keys while keeping existing ones, reverse the argument order or use setdefault().
pop() is useful when you need to remove a key and use its value at the same time. Calling pop() on a key that does not exist without a default value raises a KeyError. This behavior is the same as the list pop() method.
Python 3.9 introduced the | operator (merge) and the |= operator (update). dict1 | dict2 returns a new dictionary without modifying the originals (use |= for the same in-place behavior as update()). For inspecting dictionary keys and values, see dict.keys() / values() / items().
If you find any errors or copyright issues, please contact us.