I have a dictionary object as such:
menu = {'dinner':{'chicken':'good','beef':'average','vegetarian':{'tofu':'good','salad':{'caeser':'bad','italian':'average'}},'pork':'bad'}}
I'm trying to create a graph (decision tree) using pydot with the 'menu' data this.
'Dinner' would be the top node and its values (chicken, beef, etc.) are below it. Referring to the link, the graph function takes two parameters; a source and a node.
It would look something like this:
Except 'king' would be 'dinner' and 'lord' would be 'chicken', 'beef', etc.
My question is: How do I access a key in a value? To create a tree from this data I feel like I need to create a loop which checks if there is a value for a specific key and plots it. I'm not sure how to call values for any dictionary object (if it's not necessarily called 'dinner' or have as many elements.).
Any suggestions on how to graph it?
Your question isn't entirely clear to me, but the way of accessing a dictionary key's value in Python is simply:
That will return to you that key's value. If that key is not in the dictionary, it will return a
KeyError
, so if you are working with dictionaries and you're not sure if the key you're requesting will be in the dictionary, you have two options.If-statement (preferred):
Try-catch:
If you don't know the keys in your dictionary and you need to get them, you can simply call
dictionary.keys()
and it will return a list of all of the keys in the dictionary.Getting a the value of a dictionary key will return an object that could even be another object. Thus, to find out the value of
"tofu"
, for example, we'd do the following:Using a recursive function
You might want to consider using a recursive function (like the
visit
in my code below, so that you are able to process a general nested dictionary. In this function, you want to pass aparent
parameter to keep track of who is your incoming node. Also note you useisinstance
to check if the dictionary value of a key is a dictionary of its own, in that case you need to call yourvisit
recursively.Resulting tree structure