Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cleanest way to return a tuple containing a particular element?

Tags:

python

tuples

In python, if I have a tuple of tuples, like so:

((1, 'foo'), (2, 'bar'), (3, 'baz'))

what is the most efficient/clean/pythonic way to return the 0th element of a tuple containing a particular 1st element. I'm assuming it can be done as a simple one-liner.

In other words, how do I return 2 using 'bar'?


This is the clunky equivalent of what I'm looking for, in case it wasn't clear:

for tup in ((1, 'foo'), (2, 'bar'), (3, 'baz')):
    if tup[1] == 'bar':
        tup[0]
like image 533
sgarza62 Avatar asked Dec 28 '25 03:12

sgarza62


2 Answers

Use a list comprehension if you want all such values:

>>> lis = ((1, 'foo'), (2, 'bar'), (3, 'baz'))
>>> [x[0] for x in lis if x[1]=='bar' ]
[2]

If you want only one value:

>>> next((x[0] for x in lis if x[1]=='bar'), None)
2

If you're doing this multiple times then convert that list of tuples into a dict:

>>> d = {v:k for k,v in ((1, 'foo'), (2, 'bar'), (3, 'baz'))}
>>> d['bar']
2
>>> d['foo']
1
like image 73
Ashwini Chaudhary Avatar answered Dec 30 '25 16:12

Ashwini Chaudhary


>>> lis = ((1, 'foo'), (2, 'bar'), (3, 'baz'))
>>> dict(map(reversed, lis))['bar']
2
like image 37
Elazar Avatar answered Dec 30 '25 17:12

Elazar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!