I have a list of tuples, e.g.
>>> l = [ ("a",1), ("b",2), ("c",3) ]
and I can assume that elements are unique. Now I would like to get the first element of that tuple whose second element is 2
(which is 'b'
in this example). First attempt is:
>>> [ x for x, y in l if y == 2 ][0]
'b'
This seems somewhat cumbersome considering this creates a second list only to index the 0th element. Another way of doing this is to reverse all tuples in the given list l
and build a dictionary, then index that dictionary:
>>> dict([ (y, x) for x, y in l ])[2]
'b'
This seems even more awkward considering the amount of data shuffling involved in reversing the list and creating a dictionary. Lastly, the most verbose but perhaps fastest way to do this is to simply iterate over the list:
>>> def get(l) :
... for x, y in l :
... if y == 2 :
... return x
... assert not "Should not happen."
...
>>> get(l)
'b'
My question is: are there any better and more pythonic ways to searching through this list?