3

Given a list of strings like so:

a_list_of_keys = ['a key', 'heres another', 'oh hey a key']

What's a way to retrieve that nested series of keys from a dict like

the_value_i_want = some_dict['a key']['heres another']['oh hey a key']
Ashwini Chaudhary
  • 232,417
  • 55
  • 437
  • 487
Dustin Wyatt
  • 3,849
  • 5
  • 29
  • 55

1 Answers1

11

Use reduce with operator.getitem.

Demo:

>>> from operator import getitem
>>> d = {'a': {'b': {'c': 100}}}
>>> reduce(getitem, ['a', 'b', 'c'], d)
100
>>> d['a']['b']['c']
100
Ashwini Chaudhary
  • 232,417
  • 55
  • 437
  • 487