aberger aberger - 1 year ago 106
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']

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 Source

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)

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download