Reputation: 963
I have a graph where each node have three attributes: 'name', 'type', 'tag'. I want to create a function to check whether a node exists for a given attribute and value. For example: check if a node with attribute 'tag' = '1' exists. I wrote the following code:
def find_node(gr, att, val):
nodesAt5 = filter(lambda (n, d): d[att] == val, gr.nodes(data=True))
return nodesAt5
And I call the function as:
if not find_node(G, 'tag', w):
# do something
It gives this error:
KeyError: 'tag'
Any suggestions?
Upvotes: 1
Views: 4193
Reputation: 954
Does a node exist with attribute att
and value val
?
Let's create a test set:
import networkx as nx
G = nx.Graph()
G.add_node(0, name='zero', type='node', tag='group_0')
G.add_node(1, name='one', type='node', tag='group_1')
G.add_node(2, name='two', type='node', tag='group_2')
We want to iterate over nodes and return true if we find val
at node's attribute att
:
def find_node(gr, att, val):
return any([node for node in G.nodes(data=True) if node[1][att] == val])
Test the function:
find_node(G, 'tag', 'group_0')
[out] : True
find_node(G, 'tag', 'w')
[out] : False
Upvotes: 2
Reputation: 1031
The dictionary needs an entry with the key 'tag' already in it before you can access it. Without knowing more of the context, I can't advise further than that, though
Upvotes: 0