Accessing dictionary of dictionary in python

后端 未结 7 523
醉梦人生
醉梦人生 2021-01-22 09:47

Hi in my code there is a dictionary of dictionary.

nrec={\'bridge\': \'xapi1\', \'current_operations\': {}, \'uuid\': \'9ae5ca7d-e7d6-7a81-f619-d0ea33efb534\', \         


        
7条回答
  •  逝去的感伤
    2021-01-22 10:00

    To check if a key exists in a dictionary use:

    if 'key' in dictionary:
        # do sth
    

    So your code will be:

    if 'other_config' in nrec and 'is_guest_installer_network' in nrec['other_config'] and nrec['other_config']['is_guest_installer_network'] == 'true':
        # do sth
    

    Additionally if you want default value if the key is not present in the dict use get(key, default) method:

    nrec.get('other_config', default_value_here)
    

提交回复
热议问题