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']
注意事项:
若有多个键对应相同值,所有相关键都会被包含在结果列表中。