Dictionaries & sets
Key–value maps, uniqueness, counting, grouping, and fast lookups.
How to Use MappingProxyType to Create Immutable Dict Views in Python
Create a read-only, immutable view of a dictionary using MappingProxyType from the types module, while the original dict stays mutable.
from types import MappingProxyType
config = {"debug": True, "port": 8080}
# Create an immutable read-only view of the dict
read_only_config = MappingProxyType(config)
print(f"Read-only value: {read_only_config['debug']}")
print(f"Dict is mapping: {isinstance(read_only_config, dict)}")
# Original dict can still be …
How to Use a Frozenset as a Dict Key in Python
Demonstrates using an immutable frozenset as a hashable dictionary key, including equality and lookup with differently-ordered elements.
frozen = frozenset({"a", "b", "c"})
mapping = {frozen: "set as hashable key"}
other_frozen = frozenset(["c", "b", "a"])
print(f"Are keys equal? {frozen == other_frozen}")
print(f"Lookup with different order: {mapping[other_frozen]}")
print(f"Hash matches: {hash(frozen) == hash(other_frozen)}")
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.