Reputation: 547
I create a graph with networkx and every node has some attributes. So i want to search all nodes for a specific attributes and save every node who has this attribute in a list. I wrote the following code but im getting an error:
for node in G.nodes():
for attribute in G.node[node]['attributes']:
if attribute in question:
setOfUsers.append(node)
With this code im getting the following error:
for attribute in G.node[node]['attributes']:
KeyError: 'attributes'
So i search the forum and i tried something different to fix the problem:
for node, data in G.nodes(data=True):
if data['attributes'] == question[0]:
setOfUsers.append(node)
but i have the same error. How can iterate through the attributes?
Update: I add the node attributes with the code below. I read the attributes from a file, i split commas and newline character and then i save list in nodes
for line in file2:
line = line.strip()
words = line.split('\t')
node = int(words[0])
attributes= words[1]
splittedAttributes = attributes.split(',')
if node in G.nodes():
G.node[node]['attributes'] = splittedAttributes
Upvotes: 6
Views: 6341
Reputation: 455
are your sure you have added the info to your nodes previously? it seems like networkX doesn't known anything about your 'attributes'. by adding the info i mean something like this:
for node in G.nodes():
G.node[node]['attributes']= attributes[node]
then you can use your own code to examine them
for node in G.nodes():
for attribute in G.node[node]['attributes']:
if attribute in question:
setOfUsers.append(node)
Upvotes: 7