Jadon Smith Jadon Smith - 1 year ago 83
Python Question

Python: Returning key of dictionary

If i have a list of words:

list_of_words = ['great','debate','stronger']

And a dictionary:

dictionary = {'candidate1':['corruption','election'],'candidate2': ['lady','draintheswamp','stronger','debate'],'candidate3':['healthcare','oil']}

I have to create a function that detects the producer of the list of words.

In the example above: 'Candidate2' is the most likely producer of list_of_words

Please don't import any modules . Efficiency is not the main concern here.

Answer Source

Just iterate through the dictionary items and check if any of the items are inside the value for a given key, if so, append in a list cand that holds the candidates for which the condition holds.

Then, you return the first candidate if the length of the list is one and, if not, you return None.

In code, this looks like this:

def find_candidate():
    cand = []
    for i,j in dictionary.items():
        if any(v in j for v in list_of_words):
    return cand[0] if len(cand) == 1 else None

and when called, it returns candidate 2:


Alternatively, the list creation can be done with a comprehension:

def find_candidate():
    c = [k for k, j in dictionary.items() if any(v in j for v in list_of_words)]
    return c[0] if len(c) == 1 else None
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download