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
nbunch. An nbunch is a single node, container of nodes or None (representing all nodes). It can be a list, set, graph, etc.. To filter an nbunch so that only nodes actually in G appear, use G.
An AtlasView is a Read-only Mapping of Mappings. It is a View into a dict-of-dict data structure. The inner level of dict is read-write. But the outer level is read-only. See also AdjacencyView.
A DiGraph stores nodes and edges with optional data, or attributes. DiGraphs hold directed edges. Self loops are allowed but multiple (parallel) edges are not. Nodes can be arbitrary (hashable) Python objects with optional key/value attributes. By convention None is not used as a node.
For NetworkX, a graph with more than 100K nodes may be too large. I'll demonstrate that it can handle a network with 187K nodes in this post, but the centrality calculations were prolonged. Luckily, there are some other packages available to help us with even larger graphs.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With