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

Python如何从嵌套字典的列表字段中提取指定键值生成新字典

报错原因
  • 直接遍历SymbolInfo字典拿到的是time、data这类字符串键,你把字符串传入列表索引位置就触发了TypeError: list indices must be integers or slices, not str的报错
  • 代码里存在变量名混用(一会定义mydict一会赋值给prices)、索引路径写错的问题,['data'][x]没有指定父对象SymbolInfo,逻辑完全不成立
正确实现代码

写法1:常规for循环(易理解)

mydict = {}
# 先取SymbolInfo下的data列表,遍历列表内的每个元素字典
for item in SymbolInfo['data']:
    # 用item的id作为键,high作为值存入mydict
    mydict[item['id']] = item['high']
    # 如果需要high为浮点型而非字符串,替换为下面这句
    # mydict[item['id']] = float(item['high'])

写法2:字典推导式(更简洁)

# 一行代码完成转换,需要浮点型就把item['high']替换为float(item['high'])
mydict = {item['id']: item['high'] for item in SymbolInfo['data']}

内容的提问来源于stack exchange,提问作者Il_Marti

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 21:54:03