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

如何优雅筛选字典中Dog属性为Yes的Animal键?

优雅筛选字典中属于狗的Animal名称

问题背景

给定字典:

dictionary = {'Animal 1': {'Dog': 'Yes', 'Cat': 'No', 'Color': 'Black'},
              'Animal 2': {'Dog': 'Yes', 'Cat': 'No', 'Color': 'Brown'},
              'Animal 3': {'Dog': 'No', 'Cat': 'Yes', 'Color': 'Grey'}}

需要筛选出其中Dog字段值为Yes的Animal名称,预期输出为:['Animal 1','Animal 2']

原实现代码较为繁琐:

pd.DataFrame.from_dict(dictionary).T.loc[pd.DataFrame.from_dict(dictionary).T["Dog"]=='Yes',:].index.to_list()

优雅实现方式

1. 纯Python原生实现(无需依赖第三方库)

利用列表推导式直接遍历字典键值对完成筛选,简洁高效且逻辑清晰:

[animal for animal, attrs in dictionary.items() if attrs['Dog'] == 'Yes']

2. 优化后的Pandas实现

原代码重复创建两次DataFrame,优化后只需创建一次,同时可选更简洁的筛选写法:

方式一:复用DataFrame变量

import pandas as pd

df = pd.DataFrame.from_dict(dictionary).T
result = df[df['Dog'] == 'Yes'].index.tolist()

方式二:使用query()提升可读性

用类SQL语法编写筛选条件,让代码更贴近自然语言:

import pandas as pd

result = pd.DataFrame.from_dict(dictionary).T.query("Dog == 'Yes'").index.tolist()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 13:01:13