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
相关产品推荐
相关产品推荐

