Dictionaries & sets
Key–value maps, uniqueness, counting, grouping, and fast lookups.
Convert Lists and Dictionaries to Sets in Python
Convert lists of pairs into dictionaries and lists or dictionaries into sets using simple helper functions.
def convert_to_dict(data):
"""Convert list of tuples or lists into a dictionary."""
return dict(data)
def convert_to_set(data):
"""Convert list or dictionary into a set of its keys/values."""
if isinstance(data, dict):
return set(data.keys())
return set(data)
def convert_collection(data…
Convert namedtuple to dict with asdict in Python
Convert a namedtuple instance into an ordinary dictionary using the asdict function from the collections module's namedtuple utility.
from collections import namedtuple, asdict
def main():
# Define a namedtuple for a person
Person = namedtuple("Person", ["name", "age", "city"])
person = Person(name="Alice", age=30, city="New York")
# Convert namedtuple to dict
person_dict = asdict(person)
print("Original namedtuple…
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
…
Group Data by Key in Python with Dictionaries and Sets
Group items into a dictionary of sets using a key function, a beginner-friendly pattern for organizing data by categories.
def group_data(items, key_func):
"""Group items into a dictionary of sets based on a key function."""
grouped = {}
for item in items:
key = key_func(item)
if key not in grouped:
grouped[key] = set()
grouped[key].add(item)
return grouped
if __name__ == "__main__":
…
How to Check Data Type and Inspect Dictionaries and Sets in Python
Inspect dictionaries and sets by printing their contents, types, and sizes using a small helper function.
def check_data(data):
"""Helper to inspect dictionaries and sets."""
if isinstance(data, dict):
print(f"Dictionary with {len(data)} keys")
for key, value in data.items():
print(f" {key}: {value} ({type(value).__name__})")
elif isinstance(data, set):
print(f"Set with {le…
How to Create a Dict from Two Parallel Lists in Python (zip)
Build a dictionary by pairing elements from two parallel lists using Python's built-in zip function and dict constructor.
keys = ["name", "age", "city"]
values = ["Alice", 30, "New York"]
result = dict(zip(keys, values))
print(result)
How to Filter a Dictionary by Predicate on Values in Python
This code defines a reusable function that builds a new dictionary containing only the items whose values satisfy a given predicate function.
def filter_dict_by_predicate(d, predicate):
"""Return a new dict with only items whose value passes the predicate."""
return {k: v for k, v in d.items() if predicate(v)}
if __name__ == "__main__":
scores = {"Alice": 85, "Bob": 42, "Charlie": 91, "Diana": 60}
# Keep only values greater than or equal t…
How to Find the Intersection of Permission Sets in Python
This code defines a function that takes a list of permission sets and returns a set containing only the permissions common to all sets, with a short-circuit for empty results.
from typing import Set
def intersect_permissions(permission_sets: list[Set[str]]) -> Set[str]:
"""
Given a list of permission sets, return the common permissions
present in every set.
"""
if not permission_sets:
return set()
common = permission_sets[0]
for perm_set in permissi…
How to Map Dictionary Values with a Transformation Function in Python
Create a reusable function that applies a transformation to every value in a dictionary and returns a new dict.
def transform_dict_values(d, func):
"""Apply a transformation function to every value in a dictionary."""
return {key: func(value) for key, value in d.items()}
if __name__ == "__main__":
original = {"a": 1, "b": 2, "c": 3}
doubled = transform_dict_values(original, lambda x: x * 2)
print(doubled)
…
How to Serialize a Dictionary to a Query String in Python
Convert a Python dictionary into a URL-encoded query string using the standard library's urllib.parse.urlencode function.
import urllib.parse
def dict_to_query_string(params):
"""Serialize a dictionary to a URL query string."""
return urllib.parse.urlencode(params)
if __name__ == "__main__":
data = {
"name": "Alice Johnson",
"age": 30,
"city": "New York",
"interests": ["coding", "hiking"]
…
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.