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

前端 未结 3 888
情深已故
情深已故 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: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.

提交回复
热议问题