Is there a recursive version of the dict.get() built-in?

后端 未结 6 725
别那么骄傲
别那么骄傲 2020-11-27 05:53

I have a nested dictionary object and I want to be able to retrieve values of keys with an arbitrary depth. I\'m able to do this by subclassing dict:



        
6条回答
  •  广开言路
    2020-11-27 06:23

    You can actually achieve this really neatly in Python 3, given its handling of default keyword arguments and tuple decomposition:

    In [1]: def recursive_get(d, *args, default=None):
       ...:     if not args:
       ...:         return d
       ...:     key, *args = args
       ...:     return recursive_get(d.get(key, default), *args, default=default)
       ...: 
    

    Similar code will also work in python 2, but you'd need to revert to using **kwargs, as you did in your example. You'd also need to use indexing to decompose *args.

    In any case, there's no need for a loop if you're going to make the function recursive anyway.

    You can see that the above code demonstrates the same functionality as your existing method:

    In [2]: d = {'foo': {'bar': 'baz'}}
    
    In [3]: recursive_get(d, 'foo')
    Out[3]: {'bar': 'baz'}
    
    In [4]: recursive_get(d, 'foo', 'bar')
    Out[4]: 'baz'
    
    In [5]: recursive_get(d, 'bogus key', default='nonexistent key')
    Out[5]: 'nonexistent key'
    

提交回复
热议问题