Python Index Nested Dictionary with List

Question:

If I have a nested dictionary and varying lists:

d = {'a': {'b': {'c': {'d': 0}}}}
list1 = ['a', 'b']
list2 = ['a', 'b', 'c']
list3 = ['a', 'b', 'c', 'd']

How can I access dictionary values like so:

>>> d[list1]
{'c': {'d': 0}}
>>> d[list3]
0
Asked By: Oliver

||

Answers:

you can use functools reduce. info here. You have a nice post on reduce in real python

from functools import reduce

reduce(dict.get, list3, d)
>>> 0

EDIT: mix of list and dictioanries

in case of having mixed list and dictionary values the following is possible

d = {'a': [{'b0': {'c': 1}}, {'b1': {'c': 1}}]}
list1 = ['a', 1, 'b1', 'c']

fun = lambda element, indexer: element[indexer]
reduce(fun, list1, d)
>>> 1
Answered By: Lucas M. Uriarte

Use a short function:

def nested_get(d, lst):
    out = d
    for x in lst:
        out = out[x]
    return out

nested_get(d, list1)
# {'c': {'d': 0}}
Answered By: mozway
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.