Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to access the nodes in a networkx graph?

I am only getting <dict_keyiterator object at 0x7f300ee69410> printed; while I wish to print the neighbours of each node. Also, how to assign a number between 0-1 determining the sate of each of the neighbours.

So that the final information is something like ; node 5 has 4 neighbours which are 1,2,3,4 each with a state 0.1,0.4,0.6,0.8. I will further use these states in my calculations, so preferably an array containing this information will work. This maybe, a very trivial doubt but if someone can relate their answer with C language then it will be more than useful for me; as I am new to python!

import networkx as nx
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

G = nx.barabasi_albert_graph(100,2)

for u in G.nodes():
    neighbors = nx.neighbors(G, u)
    print(neighbors)

Edit: Answer of printing error Networkx neighbor set not printing

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

neighbors is an iterable. Without going into too much detail, iterables are the things you use in for loops.

To print out an iterable all at once, you can turn it into a list, if you know it’s finite:

print(list(neighbors))

You can also use python’s iterable unpacking syntax to pass each element individually to print:

print(*neighbors)

A more general, but sometimes more flexible approach is to run a loop over the iterable, and process each element independently:

for e in neighbors:
    print(e)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading