Python中如何从嵌套字典列表中提取指定值?
从嵌套字典列表中提取指定值的实现方案
问题背景
给定如下嵌套字典结构:
the_dic = {'k1':[1,2,3,{'tricky':['oh','man','inception',{'target':[1,2,3,'hello']}]}]}
需要提取目标值hello,并基于基础代码print(the_dic["k1"])进行扩展实现。
实现方案
可以通过逐层索引/键访问的方式直接定位到目标值,每一步根据当前元素的类型(列表用索引,字典用键)向下遍历:
- 执行
the_dic["k1"],获取外层列表:[1,2,3,{'tricky':...}] - 取列表第4个元素(索引为3):
the_dic["k1"][3],得到字典{'tricky':['oh','man','inception',{'target':...}]} - 通过键
tricky获取内层列表:the_dic["k1"][3]["tricky"],得到['oh','man','inception',{'target':...}] - 取该列表第4个元素(索引为3):
the_dic["k1"][3]["tricky"][3],得到字典{'target':[1,2,3,'hello']} - 通过键
target获取目标列表:the_dic["k1"][3]["tricky"][3]["target"],得到[1,2,3,'hello'] - 取该列表第4个元素(索引为3),即为目标值
hello
最终扩展后的完整代码:
the_dic = {'k1':[1,2,3,{'tricky':['oh','man','inception',{'target':[1,2,3,'hello']}]}]} print(the_dic["k1"][3]["tricky"][3]["target"][3])
运行后输出:hello
内容的提问来源于stack exchange,提问作者Rochhh999
相关产品推荐
相关产品推荐

