如果我有一个嵌套的字典中,我可以通过索引像这样一键搞定:通嵌套词典的位置作为参数在Python
>>> d = {'a':{'b':'c'}}
>>> d['a']['b']
'c'
我是否能够通过该索引作为函数参数?
def get_nested_value(d, path=['a']['b']):
return d[path]
编辑:我知道我的语法不正确。它是正确语法的代理。
如果我有一个嵌套的字典中,我可以通过索引像这样一键搞定:通嵌套词典的位置作为参数在Python
>>> d = {'a':{'b':'c'}}
>>> d['a']['b']
'c'
我是否能够通过该索引作为函数参数?
def get_nested_value(d, path=['a']['b']):
return d[path]
编辑:我知道我的语法不正确。它是正确语法的代理。
你可以(在Python 3或functools.reduce
)使用reduce
,但还需要你在你的密钥列表/元组经过:
>>> def get_nested_value(d, path=('a', 'b')):
return reduce(dict.get, path, d)
>>> d = {'a': {'b': 'c'}}
>>> get_nested_value(d)
'c'
>>>
(在你的情况['a']['b']
不起作用,因为['a']
是一个列表,并['a']['b']
正试图查找该元素在“b“该列表的第n个索引)
感谢,整齐的函数。我以前并没有意识到这一点! – aberger
不是真的,但通过重写你的函数体一点点,你可以通过按键作为一个元组或其他序列:
def get_nested_value(d, keys):
for k in keys:
d = d[k]
return d
d = {'a':{'b':'c'}}
print get_nested_value(d, ("a", "b"))
否。您得到'TypeError:列表索引必须是整数,而不是str'。 –
然而你可以这样做,'path = ['a','b']'并且做'd [path [0]] [path [1]]' –