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很高興幫助。 :-) –