Python return key from value, but its a list in the dictionary

So Im quiet new to python and maybe I´ve searced the wrong words on google…

My current problem:

In python you can return the key to a value when its mentioned in a dictionary.

One thing I wonder, is it possible to return the key if the used value is part of a list of values to the key? So my testing skript is the following

MainDict={'FAQ':['FAQ','faq','Faq']}


def key_return(X):
    for Y, value in MainDict.items():
        if X == value:
            return Y
    return "Key doesnt exist"

print(key_return(['FAQ', 'faq', 'Faq'])) 

print(key_return('faq'))

So I can just return the Key if I ask for the whole list, How can I return the key if I just ask for one value of that list as written for the second print? On current code I get the “Key doesnt exist” as an answer.

Answer

You can check to see if a value in the dict is a list, and if it is check to see if the value you’re searching for is in the list.

MainDict = {'FAQ':['FAQ','faq','Faq']}

def key_return(X):
    for key, value in MainDict.items():
        if X == value:
            return key
        if isinstance(value, list) and X in value:
            return key
    return "Key doesnt exist"


print(key_return(['FAQ', 'faq', 'Faq']))
print(key_return('faq'))

Note: You should also consider making MainDict a parameter that you pass to key_return instead of a global variable.