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…
How to Invert a Dictionary in Python Safely
Swap dictionary keys and values while detecting duplicate values to prevent silent data loss.
def invert_dict_safely(d):
inverted = {}
for key, value in d.items():
if value not in inverted:
inverted[value] = key
else:
raise ValueError(f"Duplicate value '{value}' would cause data loss")
return inverted
if __name__ == "__main__":
sample = {"a": 1, "b": 2,…
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…
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.