Skip to content
Advertisement

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]

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:

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

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement