aberger aberger - 28 days ago 13
Python Question

Pass nested dictionary location as parameter in Python

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.

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:

>>> 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)

Comments