python:以通用方式获取嵌套字典的值

nav*_*yad 1 python dictionary

我正在编写我的问题的简单用例,这里是:

dic =  {'a': 1, 'b': {'c': 2}}
Run Code Online (Sandbox Code Playgroud)

现在我想要一个在这个字典上运行的方法,根据键获取值.

def get_value(dic, key):
     return dic[key]
Run Code Online (Sandbox Code Playgroud)

在不同的地方,将调用此泛型方法来获取值.

get_value(dic, 'a') 将工作.

是否有可能以2 (dic['b']['c'])更通用的方式获得价值.

fal*_*tru 6

使用未绑定的方法dict.get(或dict.__getitem__)和reduce:

>>> # from functools import reduce  # Python 3.x only
>>> reduce(dict.get, ['b', 'c'], {'a': 1, 'b': {'c': 2}})
2

>>> reduce(lambda d, key: d[key], ['b', 'c'], {'a': 1, 'b': {'c': 2}})
2
Run Code Online (Sandbox Code Playgroud)

UPDATE

如果您使用dict.get并尝试访问不存在的密钥,则可以KeyError通过返回隐藏None:

>>> reduce(dict.get, ['x', 'c'], OrderedDict({'a': 1, 'b': {'c': 2}}))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: descriptor 'get' requires a 'dict' object but received a 'NoneType'
Run Code Online (Sandbox Code Playgroud)

为防止这种情况,请使用dict.__getitem__:

>>> reduce(dict.__getitem__, ['x', 'c'], OrderedDict({'a': 1, 'b': {'c': 2}}))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'x'
Run Code Online (Sandbox Code Playgroud)