Pragyan93
Pragyan93

Reputation: 721

how to check if a node is already present in Graphviz Python

How to check if a particular node is already present in the graph.

Here is what I have tried.

>>>from graphviz import Digraph
>>>dot = Digraph()
>>>dot.node('solid',xlabel='0')
>>>dot.node('liquid',xlabel='0')
>>>dot.edge('solid','liquid','melt')
>>>print (dot)

digraph {
    solid [xlabel=0]
    liquid [xlabel=0]
    solid -> liquid [label=melt]
}

>>>check = 'solid' in dot
>>>print (solid)

False

As we see here I can't directly check for the node.

I am looking for a way to check if the node has been visited/created before and if that node is visited then increment it's xlabel by 1.

Is there a way to traverse and visit each node in graphviz or do I have to write a separate code to check if a specific node is present?

Upvotes: 5

Views: 2551

Answers (2)

AlexSin
AlexSin

Reputation: 1

The method worked for me in 2020 is:

if '\tsolid' in dot.source:
    # Here you need to get the line number and know the real xlabel
    dot.body[line_number] = '\tsolid [xlabel='+str(real_xlabel)+']'

Upvotes: 0

jur
jur

Reputation: 512

Apparently the .body attribute contains a list with nodes prefixed with tab. Should you could do:

>>>print('\tsolid' in dot.body)

True

Upvotes: 1

Related Questions