Accessing dictionary of dictionary in python

后端 未结 7 525
醉梦人生
醉梦人生 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2021-01-22 10:16

    You've got the answer

    nrec["other_config"]["is_guest_installer_network"]== "true"
    

    can be written like

    if nrec.has_key("other_config") and type(nrec["other_config"]) == type({}) and nrec["other_config"].has_key("....") and nrec["other_config"]["is_guest_installer_network"]== "true":
    

    But this is sort of ugly.

    Or, as noted in the comments

    nrec.get("other_config",{}).get("is_guest_installer_network",{}) == "true"
    

    But this doesn't handle the type checking.

    Maybe best to do something like this

    def traverse(_dict, keys):
        val = _dict
        for key in keys[:-1]:
            if key in val and type(val[key]) is dict :
                val = val[key]
            else:
                return None
        return val.get(keys[-1],None)
    

提交回复
热议问题