我有一个嵌套的字典对象,我希望能够检索具有任意深度的键的值。我可以通过子类化 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'
但是,我不想必须继承 dict
才能获得此行为。是否有一些具有等效或相似行为的内置方法?如果没有,是否有提供此行为的任何标准或外部模块?
我目前正在使用 Python 2.7,但我也很想知道 3.x 解决方案。
最佳答案
执行此操作的一种非常常见的模式是使用空字典作为默认值:
d.get('foo', {}).get('bar')
如果你有多个键,你可以使用 reduce
(注意在 Python 3 中必须导入 reduce
:from functools import reduce
) 多次应用该操作
reduce(lambda c, k: c.get(k, {}), ['foo', 'bar'], d)
当然,你应该考虑把它包装成一个函数(或方法):
def recursive_get(d, *keys):
return reduce(lambda c, k: c.get(k, {}), keys, d)
关于python - 是否有内置的 dict.get() 的递归版本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28225552/