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 Parse Data Into Dictionaries and Sets in Python
Parses raw student strings into a dictionary of lists and finds unique courses using a set.
from collections import defaultdict
def parse_students(raw_data):
"""Parse raw student strings into a dictionary of lists."""
parsed = defaultdict(list)
for entry in raw_data:
name, _, course = entry.partition(":")
parsed[course.strip()].append(name.strip())
return dict(parsed)
def fi…
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…
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.