The attributes of node in the graph in networkx is just a dict
object (generally speaking, it is a dict-like structure and can be customize by setting node_attr_dict_factory
, see the doc), and nodes are just keys inside G._node
.
To share the nodes between graph, just let the nodes share the same attribute dicts. Do something like dict2 = dict1
. See this answer for the difference between dict.copy()
and dict2 = dict1
. Note that the Graph.copy
is using dict.copy()
(see source code).
I imitate the source code of copy and add_nodes_from and get the following workaround. One need to update the _node
and add the key to the _adj
attribute.
# share the node n in graph G with graph H
H._node[n] = G._node[n]
H._adj[n] = dict()
In addition, I want to find a solution specifically for whenH
always contains all nodes in G
, I tried:
H._node = G._node
H._adj = {n: dict() for n in G._adj.keys()}
In this way, if one add nodes to G(or H), they can be automatically added to H(or G). However, one will still need to update the H._adj
(or G._adj
) manually.