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

如何在嵌套字典中按匹配值筛选对应最小比较值的顶层键

嵌套字典按分组筛选最小对应值的顶层键

需求说明

给定嵌套字典,需按key_to_match的值分组,每组筛选出key_to_compare值最小的顶层键,示例输入:

d = {'first': {'key_to_match': 'a', 'key_to_compare': 50}, 
     'second': {'key_to_match': 'b', 'key_to_compare': 50}, 
     'third': {'key_to_match': 'a', 'key_to_compare': 10}}

预期输出:['second', 'third']

简洁实现方法

通过最多两次遍历完成分组与结果整理,代码逻辑清晰高效:

d = {'first': {'key_to_match': 'a', 'key_to_compare': 50}, 
     'second': {'key_to_match': 'b', 'key_to_compare': 50}, 
     'third': {'key_to_match': 'a', 'key_to_compare': 10}}

# 跟踪每个分组的最小比较值及对应顶层键
tracker = {}
for top_key, inner_dict in d.items():
    match_val = inner_dict['key_to_match']
    compare_val = inner_dict['key_to_compare']
    # 首次出现该分组,或当前值更小则更新记录
    if match_val not in tracker or compare_val < tracker[match_val][0]:
        tracker[match_val] = (compare_val, top_key)

# 按原字典中符合条件的键的出现顺序收集结果
result = []
seen_groups = set()
for top_key, inner_dict in d.items():
    match_val = inner_dict['key_to_match']
    if match_val not in seen_groups and tracker[match_val][1] == top_key:
        result.append(top_key)
        seen_groups.add(match_val)

print(result)  # 输出: ['second', 'third']

方法说明

  • 时间复杂度为O(n),仅需最多两次遍历原字典,比转元组列表再排序比较的方法更高效简洁。
  • tracker字典负责维护每个key_to_match分组的最小key_to_compare值及对应顶层键,确保每组只保留最优项。
  • 第二次遍历用于保持结果顺序与原字典中符合条件的键出现顺序一致;若无需顺序要求,直接提取tracker.values()中的顶层键即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 12:43:30