Search code examples
pythonnetworkxremovechild

remove nodes from a graph with a condition


My code starts by reading a graph containing nodes and arcs with attributes, then calculates node attributes('criticité'). After that it removes nodes under conditions.

This is my code, the type error that I receive is TypeError: unhashable type: 'dict'

#parsing
import matplotlib.pyplot as plt
import networkx as nx
G=nx.read_graphml("C:/Users/PlacisAdmin/Desktop/gephi/ex2.graphml",node_type=str)
nx.draw(G, with_labels=True)
plt.show()


# chnage nodes attributes
for u, v, weight in G.edges.data('weight'):
          if weight !=1:
             G.node[u]['criticité'] = float(G.node[u]['occurence']) * float (G.node[u]['détection']) * float (G.node[u]['gravité']) * weight
             G.node[v]['criticité'] = float(G.node[v]['occurence']) * float (G.node[v]['détection']) * float (G.node[v]['gravité']) * weight
print ("avant")
print (G.nodes.data('label'))
print (G.nodes.data('criticité'))


# calculate system crticité
for n in G.nodes():
    if G.node[n]['label']in ['1','2','3','4']:
        G.node[n]['criticité']=sum(G.node[t]['criticité'] for t in G.successors(n))

print ("après")
print (G.nodes.data('label'))
print (G.nodes.data('criticité'))

# eliminate nodes 
for d in G.nodes():
    if G.node[d]['label']in ['1','2','3','4'] and G.node[d]['criticité']> 30:
      G.remove_nodes_from(G.node[t]for t in G.successors(d) )

# show the graph
nx.draw(G, with_labels=True)
plt.show()

Solution

  • Possible duplicate of this one: https://stackoverflow.com/a/19371472/8933502

    dict is mutable and therefore cannot be hashed. You could create your own hashable dict and have it hash on its id(d) for instance (something immutable).