Search code examples
python-3.xnetworkx

Get degree of each nodes in a graph by Networkx in python


Suppose I have a data set like below that shows an undirected graph:

1   2
1   3
1   4
3   5
3   6
7   8
8   9
10  11

I have a python script like it:

for s in ActorGraph.degree():
    print(s)

that is a dictionary consist of key and value that keys are node names and values are degree of nodes:

('9', 1)
('5', 1)
('11', 1)
('8', 2)
('6', 1)
('4', 1)
('10', 1)
('7', 1)
('2', 1)
('3', 3)
('1', 3)

In networkx documentation suggest to use values() for having nodes degree. now I like to have just keys that are degree of nodes and I use this part of script but it does't work and say object has no attribute 'values':

for s in ActorGraph.degree():
        print(s.values())

how can I do it?


Solution

  • You are using version 2.0 of networkx. Which changed from using a dict for G.degree() to using a dict-like (but not dict) DegreeView. See this guide.

    To have the degrees in a list you can use a list-comprehension:

    degrees = [val for (node, val) in G.degree()]