I'm using NetworkX in my research, but I wanted to search for a node with a specific attribute, and as a result of searching for such a method, I made it.
find_specific_attribute_node.py
import networkx as nx
def find_specific_attribute_node(G, attr, value):
result = []
d = nx.get_node_attributes(G, attr)
for key, v in d.items():
if(v == value):
result.append(key)
return result
Let's run the following test program.
find_node_test_for_qiita.py
import networkx as nx
from find_specific_attribute_node import find_specific_attribute_node as find_nodes
if __name__ == '__main__':
Graph = nx.DiGraph()
Graph.add_node('a', color = 'blue')
Graph.add_node('b', color = 'red')
Graph.add_node('c', color = 'blue')
Graph.add_node('d', color = 'red')
Graph.add_node('e', color = 'blue')
Graph.add_node('f', color = 'red')
print(find_nodes(Graph, 'color', 'blue'))
Below is the execution result.
Execution result
['a', 'e', 'c']
You can see that a list consisting of node names with blue
set in the color
attribute has been acquired.
It's a very suitable one, so it has the following three arguments.
--G: Graph to be searched --attr: Attribute name you want to search --value: the value of the attr you want to find
The return value is a list of found node names.
Since it seems to be very demanding, there may actually be a method with a function similar to NetworkX. Please let me know.
Also, I haven't studied the naming conventions such as methods properly, so I'd be happy if you could tell me if there is something like "I should give it such a name" ...
Recommended Posts