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

Python中如何按值筛选嵌套字典的键?及报错排查

问题原因

你的val_list里存的是完整的子字典(比如{'name': 'EMP-0001', 'first_name': 'John', ...}),不是单独的公司名字符串。用val_list.index("Company 2")去查找字符串,自然找不到——列表里根本没有这个元素类型。

正确解法

直接遍历原字典的键值对,判断每个子字典里的company字段即可:

方式一:循环打印

for emp_name, emp_details in employee_detail_list.items():
    if emp_details['company'] == 'Company 2':
        print(emp_name)

方式二:先收集再输出

如果需要把结果存起来后续使用,可以用列表推导式:

target_employees = [name for name, details in employee_detail_list.items() if details['company'] == 'Company 2']
for emp in target_employees:
    print(emp)

运行任意一种方式,都会得到你想要的输出:

Tom Smith
Andrew Sebastian

内容的提问来源于stack exchange,提问作者Fahmi Sabila Dinnulhaq

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 01:46:08