Labelling nodes in networkx

555 views Asked by At

I'm trying to extract one set of values from a URL. This set has a unique list of numbers. The number of elements in this list should be equal to the number of nodes. So the label that these nodes get should come from the list extracted. How can this be performed using networkx?

I came across this function to label nodes:

nx.draw_networkx_labels(G,pos,labels,font_size=16)

Here, 'labels' needs to be of type dict.

import networkx as nx
from bs4 import BeautifulSoup
import matplotlib.pyplot as plt
soup = BeautifulSoup(br.response().read())
counter = 0
idvalue = []
doTags = soup.find_all("div", {"class":"classname"})
for tag in doTags:
    id = tag.find_next("span",{"class":"classname"})
    print id.string
    idvalue.append(id.string)
    counter +=1 
print counter
G = nx.Graph()
H=nx.path_graph(counter+1)
G.add_nodes_from(H) 
nx.draw(G)
nx.draw_networkx_labels(G,labels,font_size=16)
plt.show()

Is there any way I can convert 'idvalue' to dict? Or is there any other function in networkx that'll make this job easier? Please help. Thanks in advance.

1

There are 1 answers

0
nu11p01n73R On BEST ANSWER

You can convert the list, idvalue to dict using list comprehensions and dict() function

labels = dict( [ value for value in enumerate(idvalue) ] )

Example

>>> lst = ['a', 'b', 'c', 'd']
>>> dict([ x for x in enumerate(lst) ])
{0: 'a', 1: 'b', 2: 'c', 3: 'd'}

Note

  • The counter variable that you use in the program is quite useless as you can get this value from the list length.

That is instead you can write

H = nx.path_graph( len(idvalue) )