Dictionaries & sets
Key–value maps, uniqueness, counting, grouping, and fast lookups.
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 Parse Query String to Dict with Duplicate Keys in Python
Convert a URL query string into a Python dictionary, merging duplicate keys into lists while keeping single values as scalars.
from urllib.parse import parse_qs
def parse_query_to_dict(query_string):
parsed = parse_qs(query_string, keep_blank_values=True)
return {key: values if len(values) > 1 else values[0] for key, values in parsed.items()}
if __name__ == "__main__":
query = "name=John&name=Jane&age=30&city=&city=Paris&empty…
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.