I have a list of tuples, for example
>>> l = [ ("a",1), ("b",2), ("c",3) ]
and I can assume that the elements are unique. Now I would like to get the first element of this tuple, the second element of which is 2 (which in this example is 'b' ). First try:
>>> [ x for x, y in l if y == 2 ][0] 'b'
This seems a little cumbersome given that it creates a second list just to index the 0th item. Another way to do this is to undo all the tuples in a given list l and build a dictionary, and then index this dictionary:
>>> dict([ (y, x) for x, y in l ])[2] 'b'
This seems even more inconvenient, given the amount of data shuffling associated with translating the list and creating the dictionary. Finally, the most detailed, but perhaps the 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 search this list?
source share