Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list of list retrieve data

Tags:

python

list

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' )?

like image 430
Hellnar Avatar asked Mar 02 '26 09:03

Hellnar


2 Answers

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.

like image 175
Omri Barel Avatar answered Mar 04 '26 23:03

Omri Barel


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.

like image 44
zeekay Avatar answered Mar 04 '26 23:03

zeekay



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!