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

Python字典值为元组时仅用单个元组元素反向查找对应键的方法

问题背景

给定Python字典如下:

d = {
    0: ('f', 'farm'),
    1: ('m', 'mountain'),
    2: ('h', 'house'),
    3: ('t', 'forest'),
    4: ('d', 'desert')
}

需要仅通过元组值内的单个元素h,反向查找对应的键2。

实现方案

单次临时查找

如果仅偶尔需要做一次这类查找,直接遍历字典条目匹配即可,用生成器表达式实现非常简洁,匹配到第一个结果就会终止遍历,不会浪费性能:

result = next(k for k, val in d.items() if 'h' in val)
print(result) # 输出 2

如果需要处理不存在的匹配项,避免抛出StopIteration异常,可以加默认返回值:

# 匹配不到时返回None
result = next((k for k, val in d.items() if 'h' in val), None)

多次高频查找

如果需要频繁做这类反向查找,提前构建反向映射字典效率更高,仅需要遍历一次原字典,后续所有查找都是O(1)复杂度:

# 构建元组元素到键的反向映射
reverse_map = {elem: key for key, tpl in d.items() for elem in tpl}
print(reverse_map['h']) # 输出 2

如果元组内存在重复元素,需要存储所有匹配的键,可以用列表存储值:

from collections import defaultdict

reverse_map = defaultdict(list)
for key, tpl in d.items():
    for elem in tpl:
        reverse_map[elem].append(key)

print(reverse_map['h']) # 输出 [2]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 17:24:01