I have a dictionary like this:
data = {'building': ['school', 'hospital', 'church'],
        'fruits': ['mango', 'apple', 'banana'] }
Now I want to extract the key whenever a value from that key is searched. For example if user inputs mango it should print fruit How can I do this?
Advertisement
Answer
There is no way to directly do this to my knowledge, but you can try an iterative approach over the dictionary’s values:
data = {'building': ['school', 'hospital', 'church'],
        'fruits': ['mango', 'apple', 'banana'] }
def get_category(item):
    for category, contents in data.items():
        if item in contents:
            return category
    return None #Not found case
#Example
print(get_category("mango")) #Output: fruits