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

后端 未结 6 719
别那么骄傲
别那么骄傲 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:00

    There is none that I am aware of. However, you don't need to subclass dict at all, you can just write a function that takes a dictionary, args and kwargs and does the same thing:

     def recursive_get(d, *args, **kwargs):
         default = kwargs.get('default')
         cursor = d
         for a in args:
             if cursor is default: break
             cursor = recursive_get(cursor, a, default)
         return cursor 
    

    use it like this

    recursive_get(d, 'foo', 'bar')
    

提交回复
热议问题