0

I need to add an attribute to nodes in a graph of type list.

Each node needs to have its own copy of the attribute.

I need to add this attribute after my graph is created because its not necessary if a function that alters the graph is never called.

I have tried using the nx.set_node_attributes function but this gives every node the attribute I pass to the function by pointer. So every node is pointing to the same single list where as what I want is to give every node is own copy(deepcopy) of the list.

import networkx as nx
G=nx.Graph()
G.add_node(1, attributelist = [])
G.add_node(2, attributelist = [ 'a', 'b', 6])
G.nodes(data=True)

nx.set_node_attributes(G,[],'TestList')
G.nodes[1]['TestList'].append('Value')

I expect the output of the above code to be as follows:

NodeDataView({1: {'attributelist': [], 'TestList': ['Value']}, 2: {'attributelist': ['a', 'b', 6], 'TestList': []}})

But what I get is:

NodeDataView({1: {'attributelist': [], 'TestList': ['Value']}, 2: {'attributelist': ['a', 'b', 6], 'TestList': ['Value']}})

I'm fairly sure this is because the nx.set_node_attributes has just given each node a pointer to an attribute called TestList where as what I need is for every node to have its own copy of TestList.

You can see the nodes above have another attribute called attributelist. This attribute behaves as I want it to.

So doing an append function to attributelist only adds the appended value to the node specified.

G.nodes[1]['attributelist'].append('Cat')
G.nodes(data=True)

NodeDataView({1: {'attributelist': ['Cat'], 'TestList': ['Value']}, 2:{'attributelist': ['a', 'b', 6], 'TestList': ['Value']}})

1 Answer 1

1

By passing in a single list (value) for all nodes, each node is getting a reference to the same list.

Instead, you can pass in a dictionary to set_node_attributes instead of a single list:

nx.set_node_attributes(G,{1: [], 2: []},'TestList')

Or, more generally:

nx.set_node_attributes(G,{ n: [] for n in G.nodes() },'TestList')
1
  • I read the example in the documentation for networkx about using a dictionary to do what I wanted but got caught up in the fact that dictionaries are unordered and thinking I needed to keep order information. But that doesn't matter since nodes are the order information I needed.
    – Ankur
    Jun 7, 2019 at 19:43

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.