python - 是否有内置的 dict.get() 的递归版本?

标签 python dictionary recursion nested

我有一个嵌套的字典对象,我希望能够检索具有任意深度的键的值。我可以通过子类化 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/

相关文章:

c# - 从列表列表创建树 C#

python - 如何在 Windows 中执行 Python 脚本?

python - 有没有办法根据时间戳列出 AzureBlobStorage 中的 blob?

javascript - 如何在 JavaScript 中检查两个 map 是否具有相同的键集

c - 不使用 exit 语句的递归。,

algorithm - 递归 - 洪水填充算法

python - Pandas 读取 excel : do not parse numbers

python - numba jit 是否有可能减慢我的 gcd 执行速度?

python - 当键是字符串(名称)时,按字母顺序对字典进行排序

c# - 提高 F# map 插入性能