Fatemeh khodaparast
Fatemeh khodaparast

Reputation: 141

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?

Upvotes: 13

Views: 54891

Answers (3)

Rebeku
Rebeku

Reputation: 879

You can also use a dict comprehension to get an actual dictionary:

degrees = {node:val for (node, val) in G.degree()}

Upvotes: 3

I'd like to add the following: if you're initializing the undirected graph with nx.Graph() and adding the edges afterwards, just beware that networkx doesn't guarrantee the order of nodes will be preserved -- this also applies to degree(). This means that if you use the list comprehension approach then try to access the degree by list index the indexes may not correspond to the right nodes. If you'd like them to correspond, you can instead do:

degrees = [val for (node, val) in sorted(G.degree(), key=lambda pair: pair[0])]

Here's a simple example to illustrate this:

>>> edges = [(0, 1), (0, 3), (0, 5), (1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (2, 5)]
>>> g = nx.Graph()
>>> g.add_edges_from(edges)
>>> print(g.degree())
[(0, 3), (1, 4), (3, 3), (5, 2), (2, 4), (4, 2)]
>>> print([val for (node, val) in g.degree()])
[3, 4, 3, 2, 4, 2]
>>> print([val for (node, val) in sorted(g.degree(), key=lambda pair: pair[0])])
[3, 4, 4, 3, 2, 2]

Upvotes: 3

rodgdor
rodgdor

Reputation: 2630

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()]

Upvotes: 27

Related Questions