I am working to create "flowchart conversations" and using a nested dict to code them. I want to better be able to visualize the conversation flow, so I'm interested in generating a flowchart from the nested dict object.
For example, let's say we have a nested dict:
a = {
"a": {
"1": {
"1": "2",
"3": "4",
},
"2": {
"5": "6",
},
}
}
Assume all keys and values are string.
From this I want to generate the following Mermaid.js flowchart:
flowchart LR
subgraph Example
direction LR
a --> a1["1"]
a --> a2["2"]
a1 --> a11["1"]
a1 --> a13["3"]
a11 --> a112("2")
a13 --> a134("4")
a2 --> a25["5"]
a25 --> a256("6)
end
Note that the nodes in the code should be nicely named, while the string labels can be anything.
So far, I am thinking to use a variation on the generator from this answer about getting all keys from a nested dict:
def recursive_items(dictionary):
for key, value in dictionary.items():
if type(value) is dict:
yield (key, value)
yield from recursive_items(value)
else:
yield (key, value)
a = {'a': {1: {1: 2, 3: 4}, 2: {5: 6}}}
for key, value in recursive_items(a):
print(key, value)