Dictionaries & sets
Key–value maps, uniqueness, counting, grouping, and fast lookups.
Build an OrderedDict insertion order demo in Python 3
Demonstrate how OrderedDict preserves insertion order, how updates keep position, and how re-insertion moves keys to the end.
from collections import OrderedDict
def demo_ordered_dict():
# Create an OrderedDict and insert items in a specific order
ordered = OrderedDict()
ordered['banana'] = 3
ordered['apple'] = 2
ordered['cherry'] = 5
ordered['date'] = 1
print("Insertion order preserved:")
for key, value in …
How to Aggregate Order Data with Sets and Dictionaries in Python
Combine sets and dictionaries to find unique products and total quantities from a list of orders in Python.
def find_unique_products(orders):
"""Return set of all products ordered across multiple orders."""
all_products = set()
for order in orders:
all_products.update(order.get("items", []))
return all_products
def product_summary(orders):
"""Build a dictionary mapping each product to its total…
How to Sort Dictionary Keys Alphabetically in Python
This code returns a list of dictionary keys sorted alphabetically, using a case-insensitive comparison while preserving the original insertion order for keys that are equal.
data = {
"banana": 3,
"apple": 1,
"Cherry": 5,
"date": 2,
"apple": 4,
"Fig": 6,
"banana": 2,
}
def sort_dict_keys_alphabetically(d):
"""Return a list of keys sorted alphabetically (case-insensitive), stable for duplicates."""
return sorted(d.keys(), key=lambda k: k.lower())
if __n…
How to Sort a Python Dictionary by Value Descending
Sort dictionary items by their values in descending order and return a new dictionary.
def sort_dict_by_value_desc(d):
return dict(sorted(d.items(), key=lambda item: item[1], reverse=True))
if __name__ == "__main__":
sample = {"apple": 5, "banana": 2, "cherry": 8, "date": 8}
result = sort_dict_by_value_desc(sample)
print(result)
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)}")
LRU Cache with OrderedDict in Python
Implement an LRU cache using collections.OrderedDict to track insertion order and evict the least-recently-used item when capacity is exceeded.
from collections import OrderedDict
class LRUCache:
def __init__(self, capacity):
self.capacity = capacity
self.cache = OrderedDict()
def get(self, key):
if key not in self.cache:
return -1
self.cache.move_to_end(key)
return self.cache[key]
def put(sel…
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.