Home > Back-end >  Networkx: select nodes only if they have a given attribute
Networkx: select nodes only if they have a given attribute

Time:12-27

Here is a sample graph based on the code of a previous question ("How can I select nodes with a given attribute value"):

import networkx as nx

P = nx.Graph()
P.add_node("node1", at=5)
P.add_node("node2", at=5)
P.add_node("node3", at=6)

# You can select like this
selected_data = dict((n, d["at"]) for n, d in P.nodes().items() if d["at"] == 5)
# Then do what you want to do with selected_data
print(f"Node found : {len (selected_data)} : {selected_data}")

but my case is that only a few nodes possess a given attribute such as:

import networkx as nx
    
    P = nx.Graph()
    P.add_node("node1", at=5)
    P.add_node("node2")
    P.add_node("node3")
    
    # You can select like this
    selected_data = dict((n, d["at"]) for n, d in P.nodes().items() if d["at"] == 5)
    # Then do what you want to do with selected_data
    print(f"Node found : {len (selected_data)} : {selected_data}")

which as you can see only has node1 having the "at" attribute. The code as above would fail with a "Keyerror".

How would you define a function returning the list of the nodes having a given attribute?

CodePudding user response:

Here is a function that will do the job:

def get_nodes_with_attribute(graph, attribute, value):
    selected_data = []
    for n, d in graph.nodes().items():
        if attribute in d and d[attribute] == value:
            selected_data.append(n)
    return selected_data

Example usage:

import networkx as nx

P = nx.Graph()
P.add_node("node1", at=5)
P.add_node("node2")
P.add_node("node3")

selected_nodes = get_nodes_with_attribute(P, "at", 5)
print(f"Nodes found: {selected_nodes}")

# Nodes found: ['node1']
  • Related