Vadym B.
Vadym B.

Reputation: 681

In graph, access node connections by edge name

I have a knowledge base graph (built in networkx).

Here is made up example.

G = nx.DiGraph()
G.add_edge('user1', 'New York', relation = 'works at')
G.add_edge('user1', 'Boston', relation = 'from')
G.add_edge('user1', '27', relation = 'Age') 

graph relations

Between each pair of nodes I have specific relation such as 'works at', 'from', etc

I want to check if I have desired edge for specific node. For example, do I know information about where user1 works at.

Currently, I do it in a loop:

for connected_node, attributes in G['user1'].items():
    if attributes['relation'] == 'works at':
        print(True, connected_node)

Is it possible to check if a node has specific edge without loop?

And consequently get connected node by this edge?

Upvotes: 0

Views: 180

Answers (1)

yatu
yatu

Reputation: 88305

No, you'll have to iterate over the edges of the node to see if any of them matches the search criteria. The only minor improvement I can think of, is to search only among the out-edges of the node with DiGraph.out_edges:

for source, dest, d in G.out_edges('user1', data=True):
    if d.get('relation') == 'works at':
        print(f'Connected node {source} -> {dest}')
# Connected node user1 -> New York

Upvotes: 1

Related Questions