The snippet library.
Small, practical examples. Search by task or narrow things down below.
Check whether all required keys exist
Python: Compare the required key set with a dictionary key view.
Python✓ Tested
Copy nested mutable data independently
Python: Use deepcopy when changes to nested lists must not affect the original object.
Python✓ Tested
Find values missing from another collection
Python: Use a set difference to identify requested IDs absent from the available IDs.
Python✓ Tested
Find values present in exactly one set
Python: Use symmetric difference when either side can contain unmatched values.
Python✓ Tested
Find values shared by two collections
Python: Use set intersection and sort the result for deterministic display.
Python✓ Tested
Group records by a field
Python: Accumulate related values with defaultdict without checking whether each group exists.
Python✓ Tested
Invert a dictionary with unique values
Python: Swap keys and values when the values are hashable and unique.
Python✓ Tested
Keep only the most recent items
Python: Use a bounded deque to discard the oldest item as new values arrive.
Python✓ Tested
Read an optional dictionary key
Python: Use get with a fallback while leaving the dictionary unchanged.
Python✓ Tested
Remove and return a dictionary entry
Python: Use pop with a default when a missing entry is an expected condition.
Python✓ Tested