dict.pop And popitem Remove With Defaults

dict.pop removes a key and returns its value, honoring a fallback for missing keys, while popitem pops the most recently inserted pair and raises on empty maps.

PythonConfig Management

Code

pythonsnippet
21 lines
flags = {"retries": "3", "timeout": "1500", "debug": "1"}

# pop removes and returns the value; a default covers a missing key
print("retries:", flags.pop("retries"))
print("verbose:", flags.pop("verbose", "unset"))

# no default plus a missing key raises KeyError
try:
    flags.pop("verbose")
except KeyError:
    print("verbose: KeyError")

# popitem() pops the most recently inserted pair and returns a (key, value) tuple
print("popitem:", flags.popitem())
print("left:", flags)

# popitem() on an empty dict raises KeyError as well
try:
    {}.popitem()
except KeyError as err:
    print("empty:", type(err).__name__)

Output

Captured from a sandboxed run of this snippet in the build pipeline.

retries: 3
verbose: unset
verbose: KeyError
popitem: ('debug', '1')
left: {'timeout': '1500'}
empty: KeyError

How the snippet works

Top-level bindings flags hold the demo state — nothing sits inside a function scope.

Points of care

  • No package manager runs in the flow — every call lands on a built-in API.

Applying it

Every run emits labeled lines — retries:, verbose:, verbose: KeyError — when the file runs.

Statements that carry the weight

except KeyError as err:
    print("empty:", type(err).__name__)
except KeyError:
    print("verbose: KeyError")

Interactive Tools for This Topic

FAQ

What has to be installed first?
Nothing — the runtime itself provides everything the code touches. Its state lives in module-level bindings: `flags`.