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

前端 未结 3 890
情深已故
情深已故 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 14:46

    IF you can't use an exception for some reason (eg. lambda func, list comprehension, generator expression etc)

    value = a.get(b, {}).get(c, {}).get("z", None)
    

    But normally you should prefer to use the exception handler

    0 讨论(0)
  • 2021-01-23 14:59

    The python way is not to bother with the check at all.

    try:
    
        value = a[b][c]["z"]
        # do something with value
    
    except KeyError:
        print 'Sorry wrong key'
    

    here any combination of a,b,"z" maybe missing from the dictionary but they will all be caught by the exception handler. OTH, the situation where the exact key exists will result in the rest of your code being executed.

    You might also want to consider using defaultdict

    The first argument provides the initial value for the default_factory attribute; it defaults to None. All remaining arguments are treated the same as if they were passed to the dict constructor, including keyword arguments.

    This gives you the assurance that notation like a[b][c]["z"] will always execute with out errors and maybe useful in some situations, particularly where you are trying to avoid boilerplatish code.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题