源码

首页 » 归档 » 源码 » python – 是否有内置的dict.get()的递归版本…

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


我有一个嵌套的字典对象,我希望能够检索具有任意深度的键的值.我可以通过继承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解决方案.

(1)

本文由 投稿者 创作,文章地址:https://blog.isoyu.com/archives/python-shifouyouneizhidedict-getdediguibanben.html
采用知识共享署名4.0 国际许可协议进行许可。除注明转载/出处外,均为本站原创或翻译,转载前请务必署名。最后编辑时间为:9 月 20, 2019 at 02:33 上午

热评文章