Search code examples
pythongraphnetworkxdirected-acyclic-graphs

Python networkx compose graphs and preserve attributes


I have two networkx digraphs that have some node attributes. The attribute is an array. I want to compose these two graphs but the array attribute should get merged. Currently, it keeps the attributes of the second graph where the attributes conflict. Is it possible to compose two graphs and merge/update attributes if it is a list or dictionary

G=nx.DiGraph()
G.add_node(1, ids = [1,2,3])
G.add_node(2, ids = [4,5,6])
G.add_node(3, ids = [7])
G.add_edge(1,2)
G.add_edge(1,3)
H=nx.DiGraph()
H.add_node(1, ids = [2,10])
H.add_node(2, ids = [6,8])
H.add_edge(1,2)
F = nx.compose(G,H)

#Currently, it merges like
[(1, {ids=[2,10]}), (2, {ids=[6,8]}), (3, {ids=[7]})]

#I need it like this
[(1, {ids=[1,2,3,2,10]}), (2, {ids=[4,5,6,6,8]}), (3, {ids=[7]})]



Solution

  • In networkx, graphs are stored as dictionaries (of dictionaries). nx.compose basically copies the first graph, here G, and then updates the graph dictionary using the second graph, here H. As a result, the node attributes of the G are overwritten if the node is also in H. However, you can easily "repair" the node attributes after the composition:

    for node in G.nodes():
        if node in H:
            F.nodes[node]['ids'] = G.nodes[node]['ids'] + H.nodes[node]['ids']