Home > Enterprise >  Python Index Nested Dictionary with List
Python Index Nested Dictionary with List

Time:10-13

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

CodePudding user response:

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

CodePudding user response:

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}}
  • Related