Dictionaries & sets
Key–value maps, uniqueness, counting, grouping, and fast lookups.
How to Use Counter for Most Common Elements in Python
This code demonstrates how to find the most frequent elements in a list using Python's Counter class from the collections module.
from collections import Counter
def most_common_elements(items, n=1):
"""Return the n most common elements and their counts."""
counter = Counter(items)
return counter.most_common(n)
if __name__ == "__main__":
data = ["apple", "banana", "apple", "orange", "banana", "apple", "grape"]
print(most_co…
How to Use defaultdict(list) to Group Words by First Letter in Python
This code groups a list of words by their first letter using a defaultdict with a list factory, then prints each group sorted by initial.
from collections import defaultdict
def group_by_initial(words):
groups = defaultdict(list)
for word in words:
groups[word[0].upper()].append(word)
return dict(groups)
if __name__ == "__main__":
words = ["apple", "banana", "apricot", "blueberry", "cherry"]
result = group_by_initial(words)…
How to Validate Required Dict Keys in Python
Check whether a dictionary contains all required keys and return the list of missing ones using a simple list comprehension.
def find_missing_keys(data: dict, required_keys: list) -> list:
"""Return a list of required keys that are missing from the dictionary."""
return [key for key in required_keys if key not in data]
if __name__ == "__main__":
user_data = {
"name": "Alice",
"email": "alice@example.com",
…
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…
Parse Env Vars into Typed Dict in Python
Convert a list of environment variable names into a dictionary with automatically detected types (bool, int, float, or string), defaulting missing vars to None.
import os
from typing import Any, Dict
def parse_env_vars(env_names: list[str], env: Dict[str, str] | None = None) -> Dict[str, Any]:
"""Parse a list of environment variable names into a typed dict.
Each variable is parsed as:
- bool: "true"/"false" (case-insensitive)
- int: if it can be converted t…
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, …
Validate dictionary data with sets in Python
Validate a dictionary against required keys and allowed value sets, returning a list of validation errors.
def validate_data(data, required_keys, allowed_values=None):
"""
Validate a dictionary against required keys and optional allowed value sets.
Returns a list of validation errors (empty list if valid).
"""
errors = []
# Check for missing required keys
missing = set(required_keys) - set(…
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.