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

Python如何过滤字典列表中两指定键值组合重复的元素

字典列表按指定键组合去重实现

规则说明

对存储字典元素的列表执行去重,重复判定可分为两种场景:

  • 有序判定:weather_1、weather_2两个键的取值按固定顺序组合,组合完全一致才判定为重复,保留每个组合第一次出现的元素
  • 无序判定:不区分两个键的顺序,只要两个键的取值集合完全一致就算重复

有序组合去重代码

严格按照有序组合规则实现,(cold, hot)和(hot, cold)会被判定为不同组合分别保留:

def dedup_by_ordered_key(input_list):
    seen = set()
    res = []
    for item in input_list:
        # 按固定顺序取两个键的值组成可哈希元组,作为去重唯一标识
        unique_key = (item["weather_1"], item["weather_2"])
        if unique_key not in seen:
            seen.add(unique_key)
            res.append(item)
    return res

# 测试输入
input_data = [
    {'weather_1': 'cold', 'weather_2': 'hot', 'name': 'james'},
    {'weather_1': 'hot', 'weather_2': 'cold', 'name': 'james'},
    {'weather_1': 'really cold', 'weather_2': 'cold', 'name': 'james'},
    {'weather_1': 'hot', 'weather_2': 'really cold', 'name': 'james'},
    {'weather_1': 'hot', 'weather_2': 'really cold', 'name': 'james'}
]

无序组合去重代码(匹配示例期望输出)

如果需要忽略两个键的顺序,只要值的组合一致就算重复(和给出的期望输出结果完全匹配),将去重标识替换为可哈希的frozenset即可:

def dedup_by_unordered_key(input_list):
    seen = set()
    res = []
    for item in input_list:
        # frozenset不记录元素顺序,可实现无序判定
        unique_key = frozenset((item["weather_1"], item["weather_2"]))
        if unique_key not in seen:
            seen.add(unique_key)
            res.append(item)
    return res

运行该函数处理示例输入,输出结果如下:

[
    {'weather_1': 'cold', 'weather_2': 'hot', 'name': 'james'},
    {'weather_1': 'really cold', 'weather_2': 'cold', 'name': 'james'},
    {'weather_1': 'hot', 'weather_2': 'really cold', 'name': 'james'}
]

实现逻辑说明

  • 用set存储已出现的去重标识,元素查找时间复杂度为O(1),整体去重逻辑时间复杂度为O(n),处理大列表时性能优异
  • 遍历过程中仅保留第一次命中标识的元素,天然保留原列表的元素出现顺序
  • 扩展性强,后续如果需要增加更多判定键,只需要在元组/frozenset中追加对应取值即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.03 04:45:58