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]
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
>>> lis = ((1, 'foo'), (2, 'bar'), (3, 'baz'))
>>> dict(map(reversed, lis))['bar']
2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With