如何找出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
相关产品推荐
相关产品推荐

