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

如何从嵌套字典列表中高效提取price与desc字段?

提取嵌套字典列表中的price和desc到独立列表

直接用Python的列表推导式就能高效解决,不用转字符串搜索,代码简洁且可读性高:

基础实现

prices = [{'info': {'price': '2.00', 'desc': 'Up'}}, {'info': {'price': '1.50', 'desc': 'Down'}}, {'info': {'price': '3.00', 'desc': 'Down'}}, {'info': {'price': '3.00', 'desc': 'Up'}}, {'info': {'price': '8.40', 'desc': 'Down'}}, {'info': {'price': '14.20', 'desc': 'Down'}}]

# 提取所有price字段
price_list = [item['info']['price'] for item in prices]
# 提取所有desc字段
desc_list = [item['info']['desc'] for item in prices]

# 输出结果
print(price_list)  # ['2.00', '1.50', '3.00', '3.00', '8.40', '14.20']
print(desc_list)   # ['Up', 'Down', 'Down', 'Up', 'Down', 'Down']

容错版(避免键缺失报错)

如果数据中可能存在缺少info、price或desc键的情况,可以添加条件判断过滤异常项:

price_list = [item['info']['price'] for item in prices if 'info' in item and 'price' in item['info']]
desc_list = [item['info']['desc'] for item in prices if 'info' in item and 'desc' in item['info']]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 08:05:55