Skip to content Skip to sidebar Skip to footer

Python List Of List Retrieve Data

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 f

Solution 1:

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.

Solution 2:

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.

Solution 3:

If you only need the first occurrence, then don't create an intermediate list using a list comprehension as this will search the whole list.

Instead, use next() with a generator expression, which will return as soon as it finds a match:

>>> next(snd for fst, snd in data if fst == 'a')
'x'

Solution 4:

>>>data = [['a','x'], ['b','q'], ['c','z']]>>>search = 'c'>>>print [e[1] for e in data if e[0] == search]
['z']

Really, though, you want a dictionary:

>>>datadict = {'a':'x', 'b':'q', 'c':'z'}>>>search = 'c'>>>print datadict[search]
z

Solution 5:

data = [['a','x'], ['b','q'], ['c','z']]
search = 'c'for inner_list indata:
  if search in inner_list:
    print(inner_list[1])

Post a Comment for "Python List Of List Retrieve Data"