Francesco Della Vedova
Francesco Della Vedova

Reputation: 943

Use 'paths' to access different levels of nested dictionaries

I would like to define a little wrapper function that takes some sort of 'path' to access different levels of nested dictionaries:

D = {'key1': valueA,
     'key2': {'key21': valueB,
             {'key22': valueC}

In this simple example, I'd like to write a function that as argument takes, for example, a tuple like

dict_path = ('key2', 'key22')

>>>nested_getter(dict_path)
valueC

Upvotes: 2

Views: 82

Answers (2)

jamylak
jamylak

Reputation: 133544

def nested_getter(d, keys):
    return reduce(dict.get, keys, d)

Upvotes: 4

icecrime
icecrime

Reputation: 76755

D = {'key1': valueA,
     'key2': {'key21': valueB,
              'key22': valueC}}


def nested_getter(root, path):
    for elem in path:
        root = root[elem]
    return root

With this you can do:

>>> nested_getter(D, ('key2', 'key22'))
3

Upvotes: 4

Related Questions