是否有内置的dict.get()的递归版本? [英] Is there a recursive version of the dict.get() built-in?
问题描述
我有一个嵌套的字典对象,并且希望能够检索具有任意深度的键的值.我可以通过将dict
子类化:
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
:
>>> class MyDict(dict):
... def recursive_get(self, *args, **kwargs):
... default = kwargs.get('default')
... cursor = self
... for a in args:
... if cursor is default: break
... cursor = cursor.get(a, default)
... return cursor
...
>>> d = MyDict(foo={'bar': 'baz'})
>>> d
{'foo': {'bar': 'baz'}}
>>> d.get('foo')
{'bar': 'baz'}
>>> d.recursive_get('foo')
{'bar': 'baz'}
>>> d.recursive_get('foo', 'bar')
'baz'
>>> d.recursive_get('bogus key', default='nonexistent key')
'nonexistent key'
但是,我不需要子类
However, I don't want to have to subclass dict
to get this behavior. Is there some built-in method that has equivalent or similar behavior? If not, are there any standard or external modules that provide this behavior?
我目前正在使用Python 2.7,尽管我也很好奇也听说过3.x解决方案.
I'm using Python 2.7 at the moment, though I would be curious to hear about 3.x solutions as well.
推荐答案
执行此操作的一种非常常见的模式是使用空dict作为默认值:
A very common pattern to do this is to use an empty dict as your default:
d.get('foo', {}).get('bar')
如果您有多个键,则可以使用reduce
(请注意,在Python 3中,必须导入reduce
:from functools import reduce
)多次应用该操作
If you have more than a couple of keys, you could use reduce
(note that in Python 3 reduce
must be imported: from functools import reduce
) to apply the operation multiple times
reduce(lambda c, k: c.get(k, {}), ['foo', 'bar'], d)
当然,您应该考虑将其包装到一个函数(或方法)中:
Of course, you should consider wrapping this into a function (or a method):
def recursive_get(d, *keys):
return reduce(lambda c, k: c.get(k, {}), keys, d)
这篇关于是否有内置的dict.get()的递归版本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!