If I have a nested dictionary I can get a key by indexing like so:
JavaScript
x
4
1
>>> d = {'a':{'b':'c'}}
2
>>> d['a']['b']
3
'c'
4
Am I able to pass that indexing as a function parameter?
JavaScript
1
3
1
def get_nested_value(d, path=['a']['b']):
2
return d[path]
3
Obviously, this is incorrect, I get TypeError: list indices must be integers, not str
.
How can I do it correctly?
Advertisement
Answer
You can use reduce
(or functools.reduce
in python 3), but that would also require you to pass in a list/tuple of your keys:
JavaScript
1
8
1
>>> def get_nested_value(d, path=('a', 'b')):
2
return reduce(dict.get, path, d)
3
4
>>> d = {'a': {'b': 'c'}}
5
>>> get_nested_value(d)
6
'c'
7
>>>
8
(In your case ['a']['b']
doesn’t work because ['a']
is a list, and ['a']['b']
is trying to look up the element at “b“th index of that list)