How to access the nodes in a networkx graph?

Question:

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

Asked By: Formal_that

||

Answers:

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)
Answered By: Mad Physicist
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.