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

如何统计OrderedDict中以指定字符串开头的键的数量?

解决OrderedDict统计特定前缀键数量的问题

错误原因

你之前的代码报错是因为o_dict.keys()返回的是odict_keys对象(所有键的集合视图),不是单个字符串,因此无法直接调用startswith方法,需要逐个检查每个键是否符合条件。

解决方案

以下几种方法都可以实现需求:

方法1:用生成器表达式统计(高效,无需额外列表存储)

from collections import OrderedDict

# 初始化你的OrderedDict
o_dict = OrderedDict([('Name', 'First'), ('Size', '10'), ('Rate 1', '1000'), ('Rate 2', '100'), ('End', 'Last')])
# 统计以'Rate'开头的键的数量
count = sum(1 for key in o_dict if key.startswith('Rate'))
print(count)  # 输出:2

注:遍历o_dict默认就是遍历键,所以可以省略.keys()。

方法2:用列表推导式获取符合条件的键再取长度(适合需要保留符合条件的键的场景)

from collections import OrderedDict

o_dict = OrderedDict([('Name', 'First'), ('Size', '10'), ('Rate 1', '1000'), ('Rate 2', '100'), ('End', 'Last')])
matched_keys = [key for key in o_dict if key.startswith('Rate')]
count = len(matched_keys)
print(count)  # 输出:2

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 19:10:32