如何在Python字典列表中判断指定键值对是否存在?
解决方法
你的核心问题是需要判断当前字典的info和value是否同时出现在列表中同一个字典元素里,而不是分别存在于列表的任意元素中。以下是两种实现方式:
基础实现(适合小规模列表)
直接使用any()函数遍历列表,检查是否存在同时匹配info和value的字典:
# 避免使用内置类型名dict作为变量名,改为current_dict for current_dict in dicts: # 检查列表中是否有字典同时匹配info和value exists = any( item["info"] == current_dict["info"] and item["value"] == current_dict["value"] for item in list_of_dicts ) if exists: print("Already in list_of_dicts, skipping") else: print("Storing in list of dicts") list_of_dicts.append(current_dict)
高效实现(适合大规模列表)
如果list_of_dicts元素较多,预先将已有的(info, value)对存入集合,利用集合O(1)的查询效率提升性能:
# 预先生成已存在的(info, value)对集合 existing_pairs = {(item["info"], item["value"]) for item in list_of_dicts} for current_dict in dicts: current_pair = (current_dict["info"], current_dict["value"]) if current_pair in existing_pairs: print("Already in list_of_dicts, skipping") else: print("Storing in list of dicts") list_of_dicts.append(current_dict) existing_pairs.add(current_pair)
关键说明
- 原代码的错误在于
dict["info"] in list_of_dicts这种写法,因为列表中的元素是字典,直接判断字符串是否在列表中会返回False,必须逐个检查字典的对应键值。 - 两种方式都忽略了
current_dict中的type键,符合你只关注info和value的需求。
内容的提问来源于stack exchange,提问作者JJH
相关产品推荐
相关产品推荐

