知妳网 知妳网-知妳所想,懂妳所需

知妳网

知妳网知你所想为你解忧最懂你的网站

python字典值对应的键

python

python字典值对应的键

def find_keys(my_dict, target_value):

return [key for key, value in my_dict.items if value == target_value]

步骤解释:

1. 遍历字典项: 使用 `my_dict.items` 获取所有键值对。

2. 筛选匹配值: 检查每个值是否等于目标值 `target_value`。

3. 收集键: 将符合条件的键存入列表并返回。

示例用法:

python

d = {'a': 1, 'b': 2, 'c': 1}

print(find_keys(d, 1)) 输出:['a', 'c']

注意事项:

  • 字典的值可以是任意类型,但需确保比较操作符 `==` 适用于该类型。
  • 返回的键顺序与字典中的插入顺序一致(Python 3.7+)。
  • 若有多个键对应相同值,所有相关键都会被包含在结果列表中。