在 Python 中将嵌套字典位置作为参数传递

abe*_*ger 6 python parameter-passing

如果我有一个嵌套字典,我可以通过索引来获取一个键,如下所示:

>>> d = {'a':{'b':'c'}}
>>> d['a']['b']
'c'
Run Code Online (Sandbox Code Playgroud)

我可以将该索引作为函数参数传递吗?

def get_nested_value(d, path=['a']['b']):
    return d[path]
Run Code Online (Sandbox Code Playgroud)

编辑:我知道我的语法不正确。它是正确语法的代理。

Bah*_*rom 6

您可以使用reduce(或functools.reduce在 python 3 中),但这也需要您传入密钥的列表/元组:

>>> def get_nested_value(d, path=('a', 'b')):
        return reduce(dict.get, path, d)

>>> d = {'a': {'b': 'c'}}
>>> get_nested_value(d)
'c'
>>> 
Run Code Online (Sandbox Code Playgroud)

(在您的情况下['a']['b']不起作用,因为['a']是一个列表,并且['a']['b']正在尝试在该列表的“ b ”索引处查找元素)