Cryssie
Cryssie

Reputation: 3185

Finding a certain item in a list of lists in Python

I am just learning Python and I need some advice regarding searching items in a list. I have a list that contains a list of lists. How can I search for an item in a list and return the value from the same list like the example below.

Example: 
myList = [['Red', 'Tomato'], ['Green', 'Pear'], ['Red', 'Strawberry'], ['Yellow', 'Lemon']]

word = 'Green'
return Pear

Is is possible to find the first instance or the n-th instance in the list as well?

first_instance = 'Red'
return Tomato

last_instance = 'Red'
return Strawberry

Upvotes: 1

Views: 165

Answers (5)

kiriloff
kiriloff

Reputation: 26333

Use a dict comprehension, a one liner to make a dict out of a list. Then, query the dict.

>>> d={x[0]:x[1] for x in myList}

d equals {'Green': 'Pear', 'Yellow': 'Lemon', 'Red': 'Strawberry'}

>>> d['Green']
'Pear'

Upvotes: 0

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251186

You can use collections.defaultdict:

Using this once the dictionary is created it'll take only O(1) lookup to find any instance of "Red" or any other color.

>>> myList = [['Red', 'Tomato'], ['Green', 'Pear'], ['Red', 'Strawberry'], ['Yellow', 'Lemon']]
>>> from collections import defaultdict
>>> dic = defaultdict(list)
>>> for k,v in myList:
    dic[k].append(v)
...     
>>> dic['Red'][0] #first instance
'Tomato'
>>> dic['Red'][-1] #last instance
'Strawberry'
>>> dic["Yellow"][0] #first instance of Yellow
'Lemon'

Define a simple function here to handle Index errors:

>>> def solve(n, color, dic):
    try:
        return dic[color][n]
    except IndexError:
        return "Error: {0} has only {1} instances".format(color,len(dic[color]))
...     
>>> dic = defaultdict(list)
>>> for k,v in myList:
    dic[k].append(v)
...     
>>> solve(0, "Red", dic)
'Tomato'
>>> solve(-1, "Red", dic)
'Strawberry'
>>> solve(0, "Yellow", dic)
'Lemon'
>>> solve(1, "Yellow", dic)
'Error: Yellow has only 1 instances'

Upvotes: 1

Daren Thomas
Daren Thomas

Reputation: 70354

OK. All of the other answers are probably more pythonic than this. I'm just adding it, because I think when starting out, having some simple loops helps.

def find_first(key, list_of_pairs):
    for pair in list_of_pairs:
        if pair[0] == key:
            return pair[1]
    return None # hey, maybe it isn't in the list at all!

Oh, and you could define find_last as:

find_last = lambda k, lop: find_first(key, reversed(lop))

So. In python you can always go this route. Except you should really look into the list comprehensions mentioned by the other answers.

Upvotes: 0

eumiro
eumiro

Reputation: 213115

myList = [['Red', 'Tomato'], ['Green', 'Pear'], ['Red', 'Strawberry'], ['Yellow', 'Lemon']]

# first_instance_red
next(elem[1] for elem in myList if elem[0] == 'Red')

# last_instance_red
next(elem[1] for elem in myList[::-1] if elem[0] == 'Red')

Upvotes: 2

Lev Levitsky
Lev Levitsky

Reputation: 65861

You can fetch all such elements:

instances = [x[1] for x in myList if x[0] == 'Red']

And process instances[0], instances[-1], etc.

To get the first one only, I'd go with @eumoro's approach using a generator expression.

Upvotes: 3

Related Questions