user3313834
user3313834

Reputation: 7837

networkx search for a node by attributes

I look for the more elegant way to search for a node in a DiGraph from one of this attributes:

g = nx.DiGraph()
g.add_nodes_from([(1, dict(d=0, a=7)), (2, dict(d=0, a=6))])
g.add_nodes_from([(11, dict(d=1, a=4)), (12, dict(d=1, a=9))])
g.add_nodes_from([(21, dict(d=1, a=4)), (121, dict(d=2, a=7))])
g.add_edges_from([(1, 11), (1, 12), (2, 21), (12, 121)])
g.nodes.data()
# NodeDataView({1: {'d': 0, 'a': 7}, 2: {'d': 0, 'a': 6},
#              11: {'d': 1, 'a': 4}, 12: {'d': 1, 'a': 9},
#              21: {'d': 1, 'a': 4}, 121: {'d': 2, 'a': 7}})

For now I use g.nodes.data() to get node_id, attrs tuple:

def search(g, d, a):
    for nid, attrs in g.nodes.data():
        if attrs.get('d') == d and attrs.get('a') == a:
            return nid

search(g, d=1, a=9)
# 12

Upvotes: 4

Views: 6400

Answers (1)

el_Rinaldo
el_Rinaldo

Reputation: 1018

"A more elegant way" is really subjective... I propose these two approaches:

[x for x,y in g.nodes(data=True) if y['d']==1 and y['a'] == 9]
#[12]

dict(filter(lambda x: x[0] if x[1]['a'] == 9 and x[1]['d'] == 1 else False, g.nodes(data=True)))
#{12: {'a': 9, 'd': 1}}

Probably the filter function is more efficient with large amount of data. Interestingly, if you want to implement the lambda function in python 3 you need to pass through the expression above as in Python 3 tuple parameter unpacking is not supported anymore. In python 2.7 it could be probably more elegant:

dict(filter(lambda (x,y): x if y['a'] == 9 and y['d'] == 1 else False, g.nodes(data=True)))
#{12: {'a': 9, 'd': 1}}

Upvotes: 6

Related Questions