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

如何基于列表指定值过滤从JSON读取的嵌套Python字典

嵌套字典过滤实现方案

你现有代码的问题有两个:

  1. x['value']是列表类型,不能直接用['sample']做键索引,必须先遍历列表内的每个元素
  2. 嵌套路径写错,sample number字段的完整路径是元素->Test->Sample->sample number,你漏掉了Test层

正确实现代码

samplenumber_list = [226, 240, 554, 663, 324, 665, 398]

x = {'context first ': 'the energy levels are below zero', 
'count': 4, 
'value': 
[{'id': 424, 'CompletedOn': '2018-06-28T00:00:00+02:00', 'EnteredValue': '0.5', 'EnteredOn': '2018-06-28T00:00:00+02:00', 'TextValue': '0.5', 'Test': {'Specs': 'Failed', 'TestType': {'Name': 'Energy zero'}, 'Sample': {'sample number': 226}}, 'Type': {'Name': 'Energt zero'}, 'Unit': None}, 
{'id': 425, 'CompletedOn': '2018-06-28T00:00:00+02:00', 'EnteredValue': 'spot', 'EnteredOn': '2018-10-01T16:35:01.173+02:00', 'TextValue': '30', 'Test': {'Specs': 'Failed', 'TestType': {'Name': 'Energy two'}, 'Sample': {'sample number': 226}}, 'Type': {'Name': 'Energy Two'}, 'Unit': None}, 
{'id': 661, 'CompletedOn': '2018-01-10T00:00:00+01:00', 'EnteredValue': '75', 'EnteredOn': '2018-01-10T00:00:00+01:00', 'TextValue': '75', 'Test': {'Specs': 'Failed', 'TestType': {'Name': "Visuality 040"}, 'Sample': {'sample number': 239}}, 'Type': {'Name': "Visuality 040"}, 'Unit': None}, 
{'id': 673, 'CompletedOn': '2018-01-10T00:00:00+01:00', 'EnteredValue': '0', 'EnteredOn': '2018-01-10T00:00:00+01:00', 'TextValue': '0', 'Test': {'Specs': 'Passed', 'TestType': {'Name': 'scanning version'}, 'Sample': {'sample number': 240}}, 'Type': {'Name': 'Unrecorded'}, 'Unit': None}], 
'context second': 'the energy levels are still below zero'}

# 核心过滤逻辑:仅保留符合条件的value数组元素,其他字段不变
x['value'] = [item for item in x['value'] if item['Test']['Sample']['sample number'] in samplenumber_list]

# 可选:同步更新count字段为过滤后的元素数量,不需要可删除
x['count'] = len(x['value'])

逻辑说明

  • 用列表推导式遍历x['value']中的每个字典元素,判断对应sample number是否在白名单列表中,符合条件的元素才会保留
  • 过滤后的列表直接赋值回原字典的value键,其余字段完全保留原有值,符合你的需求
  • 执行后输出的结果和你期望的结构完全一致

内容的提问来源于stack exchange,提问作者Al-Andalus

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 22:06:03