0

I want to share nodes(and their attributes) between two graphs. If one updates the attributes of nodes in one graph, they can be automatically updated in another graph. Is it possible?

Why I want to so:

In fact, I want two graphs with identical nodes but different edges. I can merge them into one multigraph and add tags to the edges recording which graph they belongs to. However, I think this will make my codes such like accessing neighborhood redundant.

hellohawaii
  • 3,074
  • 6
  • 21

1 Answers1

0

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.

hellohawaii
  • 3,074
  • 6
  • 21