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.

Easy Python 3.9+ Aug 9, 2026 Dictionaries & sets 12 views 0 copies

Python code

16 lines
Python 3.9+
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), (2, 5)]
    result = build_adjacency_dict(edges)
    for node in sorted(result):
        print(f"{node}: {sorted(result[node])}")

Output

stdout
1: [2, 4]
2: [1, 3, 5]
3: [2, 4]
4: [1, 3]
5: [2]

How it works

The function starts with an empty dictionary and iterates through each edge. For every node, it initializes an empty list if the node is not already a key, so that isolated nodes still appear in the graph. Then it appends each node to the other's adjacency list, which builds an undirected graph where each connection is stored twice. Because the final output is sorted, the neighbors appear in ascending order, making the result reproducible and easy to read.

Common mistakes

  • Only adding neighbors to one direction, producing a directed graph instead of undirected.
  • Forgetting to initialize a node's adjacency list before appending, causing KeyError.
  • Omitting nodes that have no edges (if needed) by not initializing them.
  • Assuming edge order preserves neighbor order — sorting is needed for deterministic output.

Variations

  1. Use a defaultdict(list) from collections to simplify initialization.
  2. Use a set instead of list for adjacency to avoid duplicates when there are multi-edges.

Real-world use cases

  • Building a social network graph to find friends-of-friends or recommend connections.
  • Representing a road network as an adjacency dict for pathfinding algorithms like Dijkstra or BFS.
  • Mapping dependencies between tasks in a build system to detect cycles or order execution.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Dictionaries & sets

Related tutorials and quizzes for this topic.