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
  • 244,495
  • 58
  • 464
  • 504
Dustin Wyatt
  • 4,046
  • 5
  • 31
  • 60

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
  • 244,495
  • 58
  • 464
  • 504