Manipulating Graphs with NetworkX
NetworkX is a powerful pure-Python library for creating, manipulating, and analyzing graphs. This guide covers essential tasks using NetworkX.
Inspecting Directed Graphs: In-Edges and Out-Edges
For directed graphs (nx.DiGraph), you may want to know which edges point into or out of a node.
Example:
1 | |
G.in_edges(node)returns edges directed intonodeG.out_edges(node)returns edges directed out ofnode
Serializing and Deserializing Graphs
When working with graphs, you may want to save (serialize) them to a file and load (deserialize) them later. There are two common approaches in NetworkX:
A. Using JSON (Node-Link Data)
Why?
- Human-readable
- Cross-language interoperability
Serialize to JSON:
1 | |
Deserialize from JSON:
1 | |
Tip: JSON is a popular serialization format and can be easily used with web apps or other languages.
B. Using Pickle
Why?
- Fastest method in Python
- Carries all Python-specific information
- Warning: Not safe for untrusted data, and not interoperable with other languages.
Serialize using Pickle:
1 | |
Deserialize using Pickle:
1 | |
Manipulating Graphs with NetworkX
https://jifengwu2k.github.io/2026/01/31/Manipulating-Graphs-with-NetworkX/