Search code examples
pythongraphnetworkxgraph-theorycomplex-networks

Extract the key of the largest value of the node attribute


In this example, after obtaining the largest value of the node's attribute, we want to put or add its key into a separate dictionary or list. For example, if among the nodes there is 1 node whose attribute value is the highest value, 1 itself will be added to a new dictionary or list. How to do this. Thanks.

import networkx as nx

G = nx.read_gml('./networks/karate.gml',label=None)
bb = nx.betweenness_centrality(G)
cc = nx.closeness_centrality(G)
nx.set_node_attributes(G,bb,"Betweenness")
nx.set_node_attributes(G,cc,"Closeness")

for g in G.nodes():
    continue
print(max(G.nodes(data=True), key=lambda x: x[1]['Closeness']))

It should be noted that the Continue command has no special use in the above code and you should assume that we have used the print command instead. In fact, we mean the explanations we said at the beginning.

Here, node 1 has the highest feature value. Now, how to extract 1 and add it to a new list or dictionary?

(1, {'Betweenness': 0.43763528138528146, 'Closeness': 0.5689655172413793})

Solution

  • You can simply index the tuple like this:

    max_node = max(G.nodes(data=True), key=lambda x: x[1]['Closeness'])
    key = max_node[0];