Agus Sanjaya
Agus Sanjaya

Reputation: 963

Check whether a node exists in networkx

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

Answers (2)

michaelg
michaelg

Reputation: 954

Find node by attribute

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

Nathan majicvr.com
Nathan majicvr.com

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

Related Questions