Reference library

Dictionaries & sets

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

2 matches
Dictionaries & sets easy

Build adjacency dict graph from edges in Python

Convert a list of edges into an undirected adjacency dictionary, mapping each node to its neighbors, with sorted output.

graph adjacency dictionary
Python
def build_adjacency_dict(edges):
    graph = {}
    for u, v in edges:
        if u not in graph:
            graph[u] = []
        if v not in graph:
            graph[v] = []
        graph[u].append(v)
        graph[v].append(u)
    return graph

if __name__ == "__main__":
    edges = [(1, 2), (2, 3), (3, 4), (4, 1)…
12 0 Open
Dictionaries & sets easy

How to Convert a Counter to a Plain Dict with Sorted Items in Python

This code converts a collections.Counter into a regular dictionary with items sorted by key, useful for stable, readable output.

counter dict sorting
Python
from collections import Counter

def counter_to_sorted_dict(counter):
    """Convert a Counter to a plain dict with sorted items."""
    return dict(sorted(counter.items()))

if __name__ == "__main__":
    # Example usage
    data = Counter(['apple', 'banana', 'apple', 'cherry', 'banana', 'date', 'apple'])
    print("…
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.