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

如何从列表或非列表值中获取字典键?及修复最值键查找代码

问题1:根据值查找字典对应的键(值可能是单个元素或列表)

可以写一个通用函数,遍历字典的键值对,分场景判断匹配:

  • 若目标值对应字典中的列表,检查目标值是否在列表内;
  • 若目标值是单个元素,直接对比键对应的值。

示例代码:

def get_key_by_value(a_dict, target_value):
    for key, value in a_dict.items():
        if isinstance(value, list):
            if target_value in value:
                return key
        else:
            if value == target_value:
                return key
    return None

# 测试
animals = { 'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati'], 'd': ['donkey', 'dog', 'dingo']}
print(get_key_by_value(animals, 'dingo'))  # 输出 'd'
print(get_key_by_value(animals, 'baboon')) # 输出 'b'
问题2:修复查找字典中值数量最多的键的代码

你的代码核心问题是alphabet = y这行——y是遍历到的值元素(比如'dingo'),而非字典的键。另外嵌套循环统计元素数量完全没必要,用len()直接获取列表长度更高效。

修复后的代码:

animals = { 'a': ['aardvark'], 'b': ['baboon'], 'c': ['coati']}

animals['d'] = ['donkey']
animals['d'].append('dog')
animals['d'].append('dingo')

def biggest(aDict):
    max_count = 0
    result_key = ""
    for key, values in aDict.items():
        current_count = len(values)
        if current_count > max_count:
            max_count = current_count
            result_key = key
    print(max_count, result_key)
    return result_key

biggest(animals)  # 输出 3 d

修改说明:

  • 直接遍历键值对,用len(values)获取值的数量,省去嵌套循环;
  • 当当前数量超过最大值时,更新最大值并记录对应的键;
  • 逻辑简洁高效,返回结果符合预期。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 02:20:33