Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Parse nested dictionary conveniently

What is the best way to index a deeply nested dictionary? Consider the following example:

x = {'a': {'b': {'c': {'d': 1}}}}
item = x['a']['b']['c']['d']

Is there a convenient way to provide a path maybe?

# something like this
item = x.get_path('a/b/c/d')

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can build a simple approach, using the built-in library, as below:

from functools import reduce, partial
from operator import getitem

nested_get = partial(reduce, getitem)


x = {'a': {'b': {'c': {'d': 1}}}}

item = nested_get(["a", "b", "c", "d"], x)
print(item)

Output

1

UPDATE

To emulate the behavior of dict.get, use:

def nested_get(path, d, default=None):
    current = d
    for key in path:
        try:
            current = current[key]
        except KeyError:
            return default
    return current


x = {'a': {'b': {'c': {'d': 1}}}}

item = nested_get(["a", "b", "c", "d"], x)
print(item)
item = nested_get(["a", "b", "e", "d"], x)
print(item)

Output

1
None
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading