0

The code:

print(g.nodes(data=True)[0:10])

Taken from Graph tutorial does not work.

I had to make two changes to the code as described in two previous questions:

Given the two errors already reported, which seem to point to newer versions of NetworkX, is there some incompatibility with the latest version of NetworkX? I'm running it in Python 3.7.

The error I get after running the whole code and getting all the expected outputs as described in the tutorial is:

Traceback (most recent call last):
  File "Drawing-graphs.py", line 44, in <module>
    print(list(g.nodes(data=True)[0:10]))
  File "/opt/anaconda3/lib/python3.7/site-packages/networkx/classes/reportviews.py", line 277, in __getitem__
    ddict = self._nodes[n]
TypeError: unhashable type: 'slice'

The code in the tutorial is a bit long but very straight forward. It loads a graph and it prints some pieces of it. Here is all the code (without the last row it does what's expected without errors):


import itertools
import copy
import networkx as nx
import pandas as pd
import matplotlib.pyplot as plt

edgelist = pd.read_csv('https://gist.githubusercontent.com/brooksandrew/e570c38bcc72a8d102422f2af836513b/raw/89c76b2563dbc0e88384719a35cba0dfc04cd522/edgelist_sleeping_giant.csv')

# Grab node list data hosted on Gist

nodelist = pd.read_csv('https://gist.githubusercontent.com/brooksandrew/f989e10af17fb4c85b11409fea47895b/raw/a3a8da0fa5b094f1ca9d82e1642b384889ae16e8/nodelist_sleeping_giant.csv')

# Create empty graph

g = nx.Graph()

# Add edges and edge attributes

for i, elrow in edgelist.iterrows():
    g.add_edge(elrow[0], elrow[1], attr_dict=elrow[2:].to_dict())


# Add node attributes[- see question][1]
for i, nlrow in nodelist.iterrows():
    g.node[nlrow['id']].update(nlrow[1:].to_dict())

print(list(g.edges(data=True))[0:5])

# Preview first 10 nodes
print(g.nodes(data=True)[0:10])
Wang Liang
  • 4,244
  • 6
  • 22
  • 45

1 Answers1

2

You should convert the result of g.nodes() into a list since g.nodes() returns a NodeView type which can't be sliced.

print(list(g.nodes(data=True))[0:10])

this should work on python 3.7 and networkx 2.4

Michal Yanko
  • 389
  • 1
  • 6