Use python function to get key by value in dictionary and return either key or "None'

Question:

I am trying to return only the key value ’20’ but instead my function returns ‘None’. I only want it to return None if value is not in my input dictionary.

def find_key(input_dict, value):
for key,val in input_dict.items():
    if val == value:
       return key
    else: 
        return "None"

find_key({100:'a', 20:'b', 3:'c', 400:'d'}, 'b')
Asked By: Eliott Reed

||

Answers:

You can revise your function to be

def find_key(input_dict, value):
    for key, val in input_dict.items():
        if val == value: return key
    return "None"

which means the function only returns the string "None" if the loop has already ended. In your original version, the loop will exit after the first iteration because it hits a return keyword. Also, if you are returning special Python None instead of a string "None", you don’t even need to return anything explicitly because None is the default return value of a function without a return keyword.

Answered By: Mia

This returns the first matched key or None:

def find_key(input_dict, value):
    result = "None"
    for key,val in input_dict.items():
        if val == value:
            result = key
    return result
key = find_key({100:'a', 20:'b', 3:'c', 400:'d'}, 'b')
print(key) # 20
Answered By: Xie Dongfeng

Because you don’t know if your dictionary has multiple values like the one you’re looking for, you should consider returning a list of keys.

Also, returning 'None' is probably a mistake, you should consider returning None (not a string with the word ‘None’, but the actual None value), which is more useful in Python.

As a result, I’d use:

def find_keys(d, value):
    result = [key for key, x in d.items() if x == value]
    return result if result else None

Or, since [] is pretty clear if you’re returning a list, simply:

def find_keys(d, value):
    return [key for key, x in d.items() if x == value] 

Apart from covering all cases, I like this solution the best because if you read the code out loud, it’s pretty obvious what it does, as well as performing well.

Answered By: Grismar
value_key_dict = {value: key for key, value in dic7.items()}
searched_key = value_key_dict[any_value]
Answered By: eEmanuel Oviedo
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.