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
.