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

如何找出Python字典中值列表元素最多的所有对应键

功能实现方案

你需要的功能可以通过两步逻辑实现,以下是Python版本的完整代码:

from typing import Dict, List

def get_max_length_keys(input_dict: Dict[str, List[str]]) -> List[str]:
    # 处理空字典边界
    if not input_dict:
        return []
    # 计算所有值列表的最大长度
    max_length = max(len(value) for value in input_dict.values())
    # 筛选所有符合条件的键
    return [key for key, value in input_dict.items() if len(value) == max_length]

调用示例

# 测试用例
test_input = {'a':['1','2'], 'b':['1'], 'c':['1', '2']}
print(get_max_length_keys(test_input))
# 输出结果:['a', 'c']

逻辑说明

  • 先判断输入字典是否为空,避免后续求最大值时报错,空输入直接返回空列表
  • 遍历所有值计算列表长度的最大值
  • 二次遍历字典的键值对,把值长度等于最大值的键收集起来返回,自动覆盖多个键同为最大值的场景

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 04:15:05