Dictionaries & sets
Key–value maps, uniqueness, counting, grouping, and fast lookups.
How to Normalize Data in Python with Dictionaries and Sets
Normalize a list of dicts by keeping selected keys, stripping/lowercasing strings, and extracting unique sorted values using set comprehension.
def normalize_data(data, keys):
"""
Normalize a list of dictionaries by keeping only specified keys
and converting values to proper types.
"""
normalized = []
for item in data:
clean_item = {}
for key in keys:
value = item.get(key)
if isinstance(value, st…
How to Normalize Data with Dictionaries and Sets in Python
Normalize dictionary entries to a fixed set of keys and extract unique values using sets in Python.
def normalize_entry(entry: dict, valid_keys: set) -> dict:
result = {}
for key in valid_keys:
result[key] = entry.get(key, "")
return result
def unique_values(entries: list[dict], key: str) -> set:
return {entry.get(key) for entry in entries if entry.get(key) is not None}
if __name__ == "__…
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 Transform a List of Dictionaries with Sets in Python
Normalize a list of dict records — cleaning names, extracting unique tags with sets, and building a standardized result.
def transform_data(raw_records):
"""Transform a list of dict records into normalized data with sets for unique values."""
normalized = []
unique_names = set()
all_tags = set()
for record in raw_records:
# Normalize name to lowercase and strip whitespace
name = record.get("name"…
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.