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

Python如何在字典列表中匹配指定前缀并判断是否存在

实现方案

核心使用Python内置的str.startswith()方法匹配前缀,搭配any()函数实现高效判断,遍历到第一个符合条件的元素就会停止,不需要遍历全量列表。

参考代码

你给出的原始数据如下:

list_of_dicts = [{"name": 'stfdahbancssc',"status":'running'},
                 {"name": 'stfdahbancssc',"status":'running'}]

兼容无name字段的稳妥版本

如果列表里的字典可能不存在name字段,用get方法兜底避免属性报错:

if any(item.get('name', '').startswith('stf') for item in list_of_dicts):
    print("stf exists")
else:
    print("stf does not exist")

简化版本(确定所有字典都有name字段时使用)

if any(item['name'].startswith('stf') for item in list_of_dicts):
    print("stf exists")
else:
    print("stf does not exist")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 11:06:03