Having a such list of list:
data = [['a','x'], ['b','q'], ['c','z']]
search = 'c'
any(e[0] == search for e in data)
This returns boolean value but what if I want to retrieve the first appearing other pair of seach variable (in other words I want to retrieve 'x' when I search 'a' )?
You can use dict(data)['c'] to obtain the second value in the pair.
dict(data) creates a dictionary from your pairs. Note that this will return a single result, and it's not guaranteed to return the first match. But if you perform many searches and you know that you don't have duplicates, it would be faster to use a dictionary.
Otherwise, use zeekay's answer.
You could use a list comprehension instead:
>>> search = 'a'
>>> [item[1] for item in data if item[0] == search]
<<< ['x']
The right-hand part of the expression filters results so that only items where the first element equals your search value are returned.
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