Finding a certain item in a list of lists in Python

advertisements

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


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'