4
votes

I am having a problem with networkX library in python. I build a graph that initialises some nodes, edges with attributes. I also developed a method that will dynamic add a specific attribute with a specific value to a target node. For example:

 def add_tag(self,G,fnode,attr,value):
    for node in G:
        if node == fnode:
           attrs = {fnode: {attr: value}}
           nx.set_node_attributes(G,attrs)

Hence if we print the attributes of the target node will be updated

        print(Graph.node['h1'])

{'color': u'green'}

        self.add_tag(Graph,'h1','price',40)
        print(Graph.node['h1'])

{'color': u'green', 'price': 40}

My Question is How can I do the same thing for removing an existing attribute from a target node?? I can't find any method for removing/deleting attributes. I found just .update method and does not helps.

Thank you

2

2 Answers

5
votes

The attributes are python dictionaries so you can use del to remove them.

For example,

In [1]: import networkx as nx

In [2]: G = nx.Graph()

In [3]: G.add_node(1,color='red')

In [4]: G.node[1]['shape']='pear'

In [5]: list(G.nodes(data=True))
Out[5]: [(1, {'color': 'red', 'shape': 'pear'})]

In [6]: del G.node[1]['color']

In [7]: list(G.nodes(data=True))
Out[7]: [(1, {'shape': 'pear'})]
2
votes

I suppose that del method you proposed will work. You gave me a nice idea to build a remove_attribute method like that (with pop):

 def remove_attribute(self,G,tnode,attr):
    G.node[tnode].pop(attr,None)

Where tnode is the target node and attr is the attribute we want to remove.