jpm
jpm

Reputation: 184

Nested indexing in python

I have a python dict, and some (but not all) of its values are also dicts.

For example:

    d = {'a' : 1,
         'b' : {'c' : 3, 'd' : 'target_value'}
        }

What would be the best way to pass in keys to reach any target value? Something like retrieve(d, (key, nested_key, ...)) where retrieve(d, ('b','d')) would return target value.

Upvotes: 2

Views: 503

Answers (1)

Morgan Thrapp
Morgan Thrapp

Reputation: 9986

The better option here is to find a way to normalize your data structure, but if you can't for some reason, you can just access each key in order.

For example:

def nested_getter(dictionary, *keys):
    val = dictionary[keys[0]]
    for key in keys[1:]:
        val = val[key]
    return val
d = {'a' : 1,
     'b' : {'c' : 3, 'd' : 'target_value'}
    }
print(nested_getter(d, 'b', 'd'))

You could also do it recursively:

def nested_getter(dictionary, *keys):
    val = dictionary[keys[0]]
    if isinstance(val, dict):
        return nested_getter(val, *keys[1:])
    else:
        return val

Upvotes: 2

Related Questions