How to get nested dictionary key value with .get()

前端 未结 4 1526
臣服心动
臣服心动 2021-02-07 02:48

With a simple dictionary like:

myDict{\'key1\':1, \'key2\':2}

I can safely use:

print myDict.get(\'key3\')

an

相关标签:
4条回答
  • 2021-02-07 03:11

    dict.get accepts additional default parameter. The value is returned instead of None if there's no such key.

    print myDict.get('key1', {}).get('attr3')
    
    0 讨论(0)
  • 2021-02-07 03:11

    That's normal since key3 doesn't exist so

    myDict.get('key3')
    

    returns none..

    NoneType object has no attribute..

    So you have to store the value of myDict.get('key3'), test if it's not null and then use the get method on the stored item

    0 讨论(0)
  • 2021-02-07 03:27

    There is a very nice blog post from Dan O'Huiginn on the topic of nested dictionaries. He ultimately suggest subclassing dict with a class that handles nesting better. Here is the subclass modified to handle your case trying to access keys of non-dict values:

    class ndict(dict):
         def __getitem__(self, key):
             if key in self: return self.get(key)
             return self.setdefault(key, ndict())
    

    You can reference nested existing keys or ones that don't exist. You can safely use the bracket notation for access rather than .get(). If a key doesn't exist on a NestedDict object, you will get back an empty NestedDict object. The initialization is a little wordy, but if you need the functionality, it could work out for you. Here are some examples:

    In [97]: x = ndict({'key1': ndict({'attr1':1, 'attr2':2})})
    
    In [98]: x
    Out[98]: {'key1': {'attr1': 1, 'attr2': 2}}
    
    In [99]: x['key1']
    Out[99]: {'attr1': 1, 'attr2': 2}
    
    In [100]: x['key1']['key2']
    Out[100]: {}
    
    In [101]: x['key2']['key2']
    Out[101]: {}
    
    In [102]: x['key1']['attr1']
    Out[102]: 1
    
    0 讨论(0)
  • 2021-02-07 03:32

    Use exceptions:

    try:
        print myDict['key1']['attr3']
    except KeyError:
        print "Can't find my keys"
    
    0 讨论(0)
提交回复
热议问题