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

如何检查值是否在字典的列表值中并返回对应键?

字典列表值中查找对应键的实现方法

问题说明

现有字典示例:

d = {1: ['a', 'b', 'c'], 2: ['d', 'e', 'f'], 3: [1, 'i', 'j']}

需求:检查某个值x是否存在于该字典的任意列表值中,若存在则返回该列表对应的键。例如查找值1,应返回键3。已知字典值为非可迭代对象时的实现方法,不清楚值为可迭代对象时的处理方式。

实现方案

遍历字典的键值对,对每个可迭代的列表值,用in运算符判断目标值是否存在,找到后直接返回对应键即可。

基础实现代码

def get_matching_key(dictionary, target_value):
    for key, value_list in dictionary.items():
        if target_value in value_list:
            return key
    return None  # 未找到目标值时返回None

# 测试验证
test_dict = {1: ['a', 'b', 'c'], 2: ['d', 'e', 'f'], 3: [1, 'i', 'j']}
print(get_matching_key(test_dict, 1))  # 输出:3
print(get_matching_key(test_dict, 'f'))  # 输出:2
print(get_matching_key(test_dict, 'x'))  # 输出:None

拓展场景处理

如果存在多个列表包含目标值,需要返回所有匹配的键,可以用列表推导式实现:

def get_all_matching_keys(dictionary, target_value):
    return [key for key, value_list in dictionary.items() if target_value in value_list]

# 测试示例
test_dict = {1: ['a', '1'], 2: ['1', 'e'], 3: [1, 'i']}
print(get_all_matching_keys(test_dict, '1'))  # 输出:[1, 2]

关键说明

  • in运算符支持所有可迭代对象,所以这个方法不仅适用于列表,对元组、集合等可迭代的字典值同样有效。
  • 遍历过程中找到第一个匹配项就返回,效率较高,无需遍历整个字典。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 03:05:41