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.
Python code
16 linesdef 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
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
- Use a defaultdict(list) from collections to simplify initialization.
- 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
More from Dictionaries & sets
- Build a Case-Insensitive Dict with a Wrapper Class in Python medium
- Build a defaultdict histogram of categories in Python easy
- Build an OrderedDict insertion order demo in Python 3 easy
- Check Invertible Mapping for Duplicate Values in Python easy
- Compare Two Dictionaries in Python easy
- Convert Lists and Dictionaries to Sets in Python easy
Keep learning
Related tutorials and quizzes for this topic.