0
\$\begingroup\$

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.

\$\endgroup\$
6
\$\begingroup\$

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.

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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