Search code examples
pythonlistdictionaryprocessing-efficiency

Find which element of list is a key in a dictionary and what is it's value


I have a dictionary:

classes_dictionary = {'/m/09x0r': 'Speech', '/m/03qc9zr': 'Screaming'}

and a list:

labels_list = ['/m/03k3r', '/m/04rlf', '/m/07q5rw0', '/m/09x0r', '/m/0jbk']

labels_list will always contain at least one element which is a key of classes_dictionary. I wish to extract which classes are those with the lowest computational complexity. In this example, '/m/09x0r' will be translated into 'Speech'. my solution:

class_str = list()
for k in labels_list:
    print(k)
    if k in self.classes_dictionary:
        class_str.append(self.classes_dictionary[k])

I do not mind if the output is a list or any other type. Also, for generality of the question I am assuming only a single element of labels_list is a key, though the best answer may consider both cases.

Is there a more efficient way to implement this? I am asking on both, implementation efficiency


Solution

  • Using a list comprehension:

    >>> [classes_dictionary[k] for k in labels_list if k in classes_dictionary]
    ['Speech']
    

    If only one match is expected, you can use next with a generator expression to stop searching once it's found:

    >>> next(classes_dictionary[k] for k in labels_list if k in classes_dictionary)
    'Speech'