Dictionaries & sets
Key–value maps, uniqueness, counting, grouping, and fast lookups.
Find All Leaf Paths in a Nested Dict in Python
Recursively traverse a nested dictionary and yield every leaf path as a list of keys, including paths to empty dictionaries.
def find_leaf_paths(data, path=None):
if path is None:
path = []
if not isinstance(data, dict) or not data:
yield path
return
for key, value in data.items():
yield from find_leaf_paths(value, path + [key])
if __name__ == "__main__":
nested = {
"a": 1,
…
Flatten a Nested Dict to Dot Notation Keys in Python
Recursively flatten a nested dictionary into a flat dictionary with dot-separated keys using a small recursive function.
def flatten_dict(nested, parent_key='', sep='.'):
items = {}
for key, value in nested.items():
new_key = f"{parent_key}{sep}{key}" if parent_key else key
if isinstance(value, dict):
items.update(flatten_dict(value, new_key, sep))
else:
items[new_key] = value
…
Get Nested Dict Value with Default in Python
Access values deep inside a nested dictionary using a dotted path string, returning a default when any key is missing.
def get_nested(d, path, default=None):
"""Walk a nested dict along a dotted path, returning default if missing."""
current = d
for key in path.split("."):
if isinstance(current, dict) and key in current:
current = current[key]
else:
return default
return current
…
How to Count Co-occurrence Pairs in Python with Nested Dictionaries
This code counts how often any two items appear together in the same group, using a nested defaultdict keyed by item pairs.
from itertools import combinations
from collections import defaultdict
def count_cooccurrences(items_per_group):
cooccurrence = defaultdict(lambda: defaultdict(int))
for group in items_per_group:
for a, b in combinations(sorted(group), 2):
cooccurrence[a][b] += 1
cooccurrence[b…
How to Deep Merge Nested Dicts Recursively in Python
Recursively merge two Python dictionaries, with overlay values taking precedence while preserving nested structures.
def deep_merge(base, overlay):
"""
Recursively merge two dictionaries.
Values in 'overlay' take precedence over 'base'.
"""
result = base.copy()
for key, value in overlay.items():
if key in result and isinstance(result[key], dict) and isinstance(value, dict):
result[key…
How to Recursively Remove None Values from Nested Dictionaries in Python
Recursively removes all None values from nested dictionaries and lists while preserving non-None data.
def prune_none(obj):
if isinstance(obj, dict):
return {
k: prune_none(v)
for k, v in obj.items()
if v is not None and prune_none(v) is not None
}
elif isinstance(obj, list):
pruned = [prune_none(item) for item in obj]
pruned = [item for item i…
How to Set Nested Dict Value Creating Missing Keys in Python
Set a value deep inside a nested dictionary, automatically creating any missing intermediate dicts along the path.
def set_nested_value(d, keys, value):
"""
Set a value in a nested dict, creating missing intermediate keys.
Args:
d: The dict to modify
keys: Iterable of keys forming the path (e.g., ['a', 'b', 'c'])
value: The value to set at the final key
"""
current = d
for key i…
How to convert string values to int or float in Python dicts
Recursively convert string values in nested dicts and lists to ints or floats when possible, leaving other strings untouched.
def coerce_str_values(data):
"""Recursively convert string values that look like ints or floats."""
if isinstance(data, dict):
return {key: coerce_str_values(val) for key, val in data.items()}
elif isinstance(data, list):
return [coerce_str_values(item) for item in data]
elif isinstance…
Traverse Nested Dict Paths Depth-First in Python
Recursively walk a nested dictionary depth-first and yield each full path from root to leaf as lists.
def depth_first_paths(node, path=None):
if path is None:
path = []
if not isinstance(node, dict):
yield path + [node]
return
for key, value in node.items():
new_path = path + [key]
if isinstance(value, dict):
yield from depth_first_paths(value, …
Unflatten Dot Keys to Nested Dict in Python
Convert a flat dictionary with dot-separated keys into a nested dictionary structure using recursive setdefault loops.
def unflatten_dot_keys(flat_dict):
result = {}
for flat_key, value in flat_dict.items():
parts = flat_key.split(".")
current = result
for part in parts[:-1]:
current = current.setdefault(part, {})
current[parts[-1]] = value
return result
if __name__ == "__main_…
Browse by section
Each section groups closely related Python snippets.
Dictionaries & sets — Python code examples
What you will find here
This page collects dictionaries & sets snippets — short, copy-ready Python you can paste into our free online IDE and run without installing anything. Each sample includes a plain-English explanation and the full source code.
Samples vs tutorials and challenges
Samples are quick reference — one concept per page. For step-by-step teaching, use our Python tutorials. To test yourself, try quizzes or coding challenges. Clean up style with the Python formatter.