0

If I have a nested dictionary mydict={'a1':{'b1':1}, 'a2':2} and a list of indexes index = ['a1', 'b1'] leading to an inner value, is there a pythonic / one-liner way to get that value, i.e. without resorting to a verbose loop like:

d = mydict
for idx in index:
    d = d[idx]
print(d)
DeepSpace
  • 78,697
  • 11
  • 109
  • 154
npit
  • 2,219
  • 2
  • 19
  • 25

1 Answers1

0

You can use functools.reduce.

>>> from functools import reduce
>>> mydict = {'a1':{'b1':1}, 'a2':2}
>>> keys = ['a1', 'b1']
>>> reduce(dict.get, keys, mydict)
1

dict.get is a function that takes two arguments, the dict and a key (and another optional argument not relevant here). mydict is used as the initial value.

In case you ever need the intermediary results, use itertools.accumulate.

>>> from itertools import accumulate
>>> list(accumulate([mydict] + keys, dict.get))
[{'a1': {'b1': 1}, 'a2': 2}, {'b1': 1}, 1]

Unfortunately, the function does not take an optional initializer argument, so we are prepending mydict to keys.

timgeb
  • 76,762
  • 20
  • 123
  • 145