Dictionary object to decision tree in Pydot

前端 未结 2 1846
礼貌的吻别
礼貌的吻别 2021-01-02 17:44

I have a dictionary object as such:

menu = {\'dinner\':{\'chicken\':\'good\',\'beef\':\'average\',\'vegetarian\':{\'tofu\':\'good\',\'salad\':{\'caeser\':\'b         


        
2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-02 18:20

    Your question isn't entirely clear to me, but the way of accessing a dictionary key's value in Python is simply:

    dictionary[key]
    

    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):

    if key in dictionary:
        return dictionary[key]
    

    Try-catch:

    try:
        return dictionary[key]
    except KeyError:
        pass
    

    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:

    menu['dinner']['vegetarian']['tofu']
    # returns value 'good'
    

提交回复
热议问题