要遍历所有的值并找到对应的键,可以使用以下方法:
my_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 2}
target_value = 2
for key, value in my_dict.items():
if value == target_value:
print("对应的键为:", key)
输出结果:
对应的键为: b
对应的键为: d
my_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 2}
target_value = 2
keys = [key for key, value in my_dict.items() if value == target_value]
print("对应的键为:", keys)
输出结果:
对应的键为: ['b', 'd']
这两种方法都可以遍历所有的值并找到对应的键,具体选择哪种方法取决于你的具体需求和编程风格。