是否有递归版本的 dict.get() 内置? [英] Is there a recursive version of the dict.get() built-in?

查看:25
本文介绍了是否有递归版本的 dict.get() 内置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个嵌套的字典对象,我希望能够检索任意深度的键值.我可以通过子类化 dict 来做到这一点:

<预><代码>>>>类 MyDict(dict):... def recursive_get(self, *args, **kwargs):... default = kwargs.get('default')...游标=自我... 对于 a in args:...如果光标是默认值:break... cursor = cursor.get(a, default)...返回光标...>>>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')'巴兹'>>>d.recursive_get('bogus key', default='nonexistent key')'不存在的钥匙'

但是,我不想必须对 dict 进行子类化来获得这种行为.是否有一些具有等效或相似行为的内置方法?如果没有,是否有任何标准或外部模块提供这种行为?

我目前使用的是 Python 2.7,不过我也很想知道 3.x 解决方案.

解决方案

一个非常常见的模式是使用一个空的 dict 作为你的默认值:

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)

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?

I'm using Python 2.7 at the moment, though I would be curious to hear about 3.x solutions as well.

解决方案

A very common pattern to do this is to use an empty dict as your default:

d.get('foo', {}).get('bar')

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆