Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 276
aberger Avatar asked Nov 07 '16 15:11

aberger


2 Answers

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)

like image 111
Bahrom Avatar answered Nov 14 '22 23:11

Bahrom


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"))
like image 35
Kevin Avatar answered Nov 14 '22 23:11

Kevin