Dictionary Methods
pop()
Remove and return the value for a specified key.
dict.pop(key, default=None)
dict.pop() removes the specified key from the dictionary and returns its corresponding value.
If the key is missing and a default is given, that default is returned. If no default is provided, a KeyError is raised.
Parameters
| Name | Description |
|---|---|
| key | The key to remove. |
| default | Optional fallback value returned if the key is not in the dictionary. |
Returns
The removed value, or the default value if the key was missing.
Try it
Run it and change it
config = {"port": 8080, "debug": True, "temp_key": "abc"}
removed = config.pop("temp_key")
missing = config.pop("timeout", 30)
print("Removed:", removed)
print("Missing fallback:", missing)
print("Remaining:", list(config.keys()))Worth knowing
- Safe deletion: Using
dict.pop(key, None)is a common idiom to delete a key without having to check withif key in dict:first.