深度阅读

How to get the key corresponding to a value in a Python dictionary?

作者
作者
2023年08月22日
更新时间
15.59 分钟
阅读时间
0
阅读量

To get the key corresponding to a value in a Python dictionary, you can use a dictionary comprehension or loop through the key-value pairs in the dictionary. Here are some examples:

Using a dictionary comprehension:

my_dict = {'key1': 10, 'key2': 45, 'key3': 23}
search_value = 45
result = [key for key, value in my_dict.items() if value == search_value]
if result:
    print("Key(s) for the value:", result)
else:
    print("Value does not exist in dictionary")

In this example, a dictionary comprehension is used to create a list of keys that have the value 45. If the resulting list is non-empty, it means that one or more keys with the given value exist in the dictionary.

Using a for-loop:

my_dict = {'key1': 10, 'key2': 45, 'key3': 23}
search_value = 45
result = []
for key, value in my_dict.items():
    if value == search_value:
        result.append(key)
if result:
    print("Key(s) for the value:", result)
else:
    print("Value does not exist in dictionary")

In this example, a for-loop is used to loop through the key-value pairs in the dictionary and append the keys that have the value 45 to a list. If the resulting list is non-empty, it means that one or more keys with the given value exist in the dictionary.

Note that if the dictionary contains duplicate values, both methods above will return a list of keys. If you only want to get the first key that matches the value, you can modify the code to break out of the loop or return the first element of the resulting list, depending on your preferences.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。