How to check if a key exists in an inner dictionary inside a dictionary in python?

前端 未结 3 889
情深已故
情深已故 2021-01-23 14:41

There is a python dictionary:

a = {b:{c:{\"x\":1, \"y\":2, \"z\":3}}}

I want to know if a[b][c][\"z\"] exists, but yet I don\'t kn

3条回答
  •  [愿得一人]
    2021-01-23 15:02

    Why don't you use your own function, it gives you flexibility, Recursion!

    def _finditem(obj, key):
        if key in obj: return obj[key]
        for k, v in obj.items():
            if isinstance(v,dict):
                item = _finditem(v, key)
                if item is not None:
                    return item
    

    Of course, that will fail if you have None values in any of your dictionaries. In that case, you could set up a sentinel object() for this function and return that in the case that you don't find anything -- Then you can check against the sentinel to know if you found something or not.

提交回复
热议问题