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

如何在Python字典列表中按值筛选并输出指定元素

筛选字典列表中count等于1的元素

最简单的实现方式:列表推导式

Python里列表推导式是处理这类筛选需求最简洁高效的写法,一行代码就能得到结果:

首先定义你的原始字典列表:

word_list = [
    {'word': 'the', 'count': 19}, 
    {'word': 'and', 'count': 14}, 
    {'word': 'he', 'count': 7}, 
    {'word': 'left', 'count': 1}, 
    {'word': 'dead', 'count': 1}, 
    {'word': 'its', 'count': 1}, 
    {'word': 'head', 'count': 1}, 
    {'word': 'galumphing', 'count': 1}, 
    {'word': 'arm', 'count': 1}, 
    {'word': 'beamish', 'count': 1}, 
    {'word': 'boy', 'count': 1}, 
    {'word': 'o', 'count': 1}
]

执行筛选:

result = [item for item in word_list if item['count'] == 1]

普通for循环实现(符合你提到的循环写法)

如果更习惯用显式的for循环,也可以这样写:

result = []
for item in word_list:
    # 判断当前字典的count值是否为1
    if item['count'] == 1:
        result.append(item)

验证输出

打印result就能得到你期望的结果:

print(result)
# 输出:
# [{'word': 'left', 'count': 1}, 
#  {'word': 'dead', 'count': 1}, 
#  {'word': 'its', 'count': 1}, 
#  {'word': 'head', 'count': 1}, 
#  {'word': 'galumphing', 'count': 1}, 
#  {'word': 'arm', 'count': 1}, 
#  {'word': 'beamish', 'count': 1}, 
#  {'word': 'boy', 'count': 1}, 
#  {'word': 'o', 'count': 1}]

内容的提问来源于stack exchange,提问作者Damon O'Neil

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 19:51:28