0

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()
lebelinoz
  • 4,890
  • 10
  • 33
  • 56
  • for future reference, it is helpful to provide the full error "traceback". That way we know exactly what command is causing the error. – Joel Feb 20 '18 at 21:49

2 Answers2

1

I believe your error is in this line:

G.remove_nodes_from(G.node[t]for t in G.successors(d) )

G.node[t] is a dict containing all of the attributes of the node t. So it is looking for a node which is the dict of attributes of node t. But, networkx doesn't allow nodes to be dicts. Hence it's giving you an error message when it starts looking for the node to delete.

You almost certainly mean to be calling

G.remove_nodes_from(t for t in G.successors(d))
Joel
  • 22,598
  • 6
  • 69
  • 93
-2

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).

Samuel GIFFARD
  • 796
  • 6
  • 22
  • @firas-borcheni If this is an accepted answer, don't forget to flag it as correct. If it's not, please ask in more details. This will help future readers. – Samuel GIFFARD Feb 20 '18 at 16:10