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.
Code
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: KeyErrorHow 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
Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- What has to be installed first?
- Nothing — the runtime itself provides everything the code touches. Its state lives in module-level bindings: `flags`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.