If I have a nested dictionary I can get a key by indexing like so:
>>> d = {'a':{'b':'c'}}
>>> d['a']['b']
'c'
Am I able to pass that indexing as a function parameter?
def get_nested_value(d, path=['a']['b']):
return d[path]
EDIT: I am aware my syntax is incorrect. It's a proxy for the correct syntax.
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:
>>> def get_nested_value(d, path=('a', 'b')):
return reduce(dict.get, path, d)
>>> d = {'a': {'b': 'c'}}
>>> get_nested_value(d)
'c'
>>>
(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)
Not really, but by rewriting your function body a little bit, you can pass the keys as a tuple or other sequence:
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"))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With