Reference library

Dictionaries & sets

Key–value maps, uniqueness, counting, grouping, and fast lookups.

6 matches
Dictionaries & sets easy

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.

ordereddict dictionaries insertion-order
Python
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 …
13 0 Open
Dictionaries & sets easy

How to Use ChainMap for Layered Config Lookup in Python

This code demonstrates using collections.ChainMap to combine multiple dictionaries into a single layered lookup, where earlier maps override later ones.

chainmap configuration collections
Python
from collections import ChainMap

defaults = {"theme": "light", "lang": "en", "debug": False}
user = {"lang": "de", "auto_save": True}
runtime = {"debug": True}

config = ChainMap(runtime, user, defaults)

if __name__ == "__main__":
    print("theme:", config["theme"])
    print("lang:", config["lang"])
    print("deb…
14 0 Open
Dictionaries & sets easy

How to Use Counter for Most Common Elements in Python

This code demonstrates how to find the most frequent elements in a list using Python's Counter class from the collections module.

collections counter frequency
Python
from collections import Counter

def most_common_elements(items, n=1):
    """Return the n most common elements and their counts."""
    counter = Counter(items)
    return counter.most_common(n)

if __name__ == "__main__":
    data = ["apple", "banana", "apple", "orange", "banana", "apple", "grape"]
    print(most_co…
13 0 Open
Dictionaries & sets easy

How to Use Dictionaries and Sets in Python for Beginners

Demonstrates Python dictionary operations and set operations with examples, including access, modification, defaults, and set algebra.

dictionary set beginner
Python
def demonstrate_collections():
    # Dictionary basics
    student = {
        "name": "Alice",
        "age": 20,
        "courses": ["Math", "Physics"]
    }
    print("Dictionary:", student)

    # Access and modify
    student["age"] = 21
    student["grade"] = "A"
    print("Modified:", student)

    # Get with d…
11 0 Open
Dictionaries & sets easy

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.

frozenset dictionary hashable
Python
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)}")
13 0 Open
Dictionaries & sets easy

Multiset with Counter update and elements in Python

Demonstrates using collections.Counter as a multiset: updating counts with update() and iterating elements() to get repeated items.

counter multiset collections
Python
from collections import Counter

multiset = Counter(['apple', 'banana', 'apple'])

multiset.update(['banana', 'cherry', 'apple'])

print("Elements after update:", sorted(multiset.elements()))
print("Counts:", dict(multiset))
print("Most common:", multiset.most_common(2))
13 0 Open

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.