Finding a key from values (which are list) in dict I have a dictionary:

x = {'a': [1, 2, 3], 'b': [4, 5, 6]}


and I have to extract a key based on an input. For example assume it is 3, so my output should be 'a'.

Here's my code:

x = {'a': [1, 2, 3], 'b': [4, 5, 6]}

n = 3

output = [k for k, v in x.items() if n in v]

print(output[0])


Can it be done more efficiently?

Elements in the lists are unique, i.e. the value 3 will only be in one list.
Given that you only want the first match, it would be more efficient to stop when you reach it:

output = next(key for key, value in x.items() if n in value)


Note that this will throw a StopIteration exception if there is no matching key, rather than the IndexError your current code throws.

If you need to do this multiple times, you could build a reverse map:

x_reversed = {num: key for key, value in x.items() for num in value}


then the lookup is a trivial x_ reversed[n] However, note the error case changes again, to KeyError.