Python 字典:根据值获取键的两种方法
在 Python 中,可以通过字典的值来获取对应的键。有多种方法可以实现这个功能,下面是其中两种常见的方法:
- 使用循环遍历字典的键值对,判断值是否与目标值相等,如果相等则返回对应的键。
def get_key_by_value(dictionary, value):
for key, val in dictionary.items():
if val == value:
return key
return None # 如果没有找到对应的键,则返回None或者其他合适的值
示例用法:
my_dict = {'a': 1, 'b': 2, 'c': 3}
key = get_key_by_value(my_dict, 2)
print(key) # 输出 'b'
- 使用字典的
keys()和values()方法,将字典的键和值转换为列表,然后使用索引来获取对应的键。
def get_key_by_value(dictionary, value):
keys = list(dictionary.keys())
values = list(dictionary.values())
if value in values:
index = values.index(value)
return keys[index]
return None # 如果没有找到对应的键,则返回None或者其他合适的值
示例用法:
my_dict = {'a': 1, 'b': 2, 'c': 3}
key = get_key_by_value(my_dict, 2)
print(key) # 输出 'b'
以上两种方法都可以根据字典的值获取对应的键。根据实际情况选择其中一种方法即可。
原文地址: https://www.cveoy.top/t/topic/quD7 著作权归作者所有。请勿转载和采集!