1
\$\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.

jonrsharpe
14k2 gold badges36 silver badges62 bronze badges
asked Apr 22, 2019 at 8:24
\$\endgroup\$

1 Answer 1

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.

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

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.