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]


Can it be done more efficiently?

Elements in the lists are unique, i.e. the value 3 will only be in one list.


1 Answer 1


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.

  • \$\begingroup\$ Thanks. As I have to do it only once, I would go for the first solution. \$\endgroup\$
    – Sociopath
    Apr 22, 2019 at 11:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.