Eliott Reed
Eliott Reed

Reputation: 321

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

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')

Upvotes: 1

Views: 9883

Answers (4)

eEmanuel Oviedo
eEmanuel Oviedo

Reputation: 69

value_key_dict = {value: key for key, value in dic7.items()}
searched_key = value_key_dict[any_value]

Upvotes: 0

Grismar
Grismar

Reputation: 31339

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.

Upvotes: 2

Xie Dongfeng
Xie Dongfeng

Reputation: 131

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

Upvotes: 2

Mia
Mia

Reputation: 2676

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.

Upvotes: 3

Related Questions