You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python中如何从嵌套字典列表中提取指定值?

从嵌套字典列表中提取指定值的实现方案

问题背景

给定如下嵌套字典结构:

the_dic = {'k1':[1,2,3,{'tricky':['oh','man','inception',{'target':[1,2,3,'hello']}]}]}

需要提取目标值hello,并基于基础代码print(the_dic["k1"])进行扩展实现。

实现方案

可以通过逐层索引/键访问的方式直接定位到目标值,每一步根据当前元素的类型(列表用索引,字典用键)向下遍历:

  1. 执行the_dic["k1"],获取外层列表:[1,2,3,{'tricky':...}]
  2. 取列表第4个元素(索引为3):the_dic["k1"][3],得到字典{'tricky':['oh','man','inception',{'target':...}]}
  3. 通过键tricky获取内层列表:the_dic["k1"][3]["tricky"],得到['oh','man','inception',{'target':...}]
  4. 取该列表第4个元素(索引为3):the_dic["k1"][3]["tricky"][3],得到字典{'target':[1,2,3,'hello']}
  5. 通过键target获取目标列表:the_dic["k1"][3]["tricky"][3]["target"],得到[1,2,3,'hello']
  6. 取该列表第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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 20:45:56