3
给出一个字符串列表,像这样:如何从键值列表中检索嵌套字典值?
a_list_of_keys = ['a key', 'heres another', 'oh hey a key']
什么是检索嵌套一系列的键从字典一样
the_value_i_want = some_dict['a key']['heres another']['oh hey a key']
给出一个字符串列表,像这样:如何从键值列表中检索嵌套字典值?
a_list_of_keys = ['a key', 'heres another', 'oh hey a key']
什么是检索嵌套一系列的键从字典一样
the_value_i_want = some_dict['a key']['heres another']['oh hey a key']
使用reduce
与operator.getitem
的方式。
演示:
>>> from operator import getitem
>>> d = {'a': {'b': {'c': 100}}}
>>> reduce(getitem, ['a', 'b', 'c'], d)
100
>>> d['a']['b']['c']
100
尼斯。我想我需要getitem之类的东西,甚至不知道getitem是否存在。谢谢! –
@DustinWyatt很高兴帮助。 :-) –