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

如何检查字典的列表中指定值是否唯一并定位其所在键?

查找字典列表中目标值在指定键外的所属键

要实现这个需求,你可以遍历字典中除指定排除键之外的所有键,检查对应列表是否包含目标值,收集符合条件的键即可。

以你提供的示例为例,用Python实现的代码如下:

def find_keys_exclude_target(d, target_val, exclude_key):
    result = []
    for key, lst in d.items():
        if key != exclude_key and target_val in lst:
            result.append(key)
    return result

# 示例字典
sample_dict = {1: [3, 4, 5], 2: [4], 3: [5], 6: [3, 5, 9], 8: [3, 8]}
# 查找值3,排除键1的结果
print(find_keys_exclude_target(sample_dict, 3, 1))  # 输出: [6, 8]

代码说明

  • 函数find_keys_exclude_target接收三个参数:目标字典d、要查找的目标值target_val、需要排除的键exclude_key
  • 遍历字典的键值对,跳过排除键,若当前列表包含目标值,则将键加入结果列表
  • 最后返回收集到的所有符合条件的键

如果需要同时排除多个键,只需把exclude_key改成可迭代对象(比如集合、列表),调整判断条件即可:

def find_keys_exclude_targets(d, target_val, exclude_keys):
    result = []
    for key, lst in d.items():
        if key not in exclude_keys and target_val in lst:
            result.append(key)
    return result

# 示例:排除键1和6,查找值3
print(find_keys_exclude_targets(sample_dict, 3, {1, 6}))  # 输出: [8]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 21:55:22