Ziva
Ziva

Reputation: 3501

Python: take an entry from a list of named tuples if contains particular attribute value

I have a list of namedtuples as below

fruits = Fruits['type', 'color', 'weight', 'sweetness']
f1 = fruits('apple', 'red', 1.89, 5)
f1 = fruits('pear', 'green', 2.89, 7)
f1 = fruits('banana', 'yellow', 2.01, 10)

l = [f1, f2, f3]

Now, I want to have a function which returns a particular namedtuple from the list given a type. I wrote this function using a for loop, but is it possible to do it better (faster or without for loop)?

def take_fruit(type, all_fruits):
    for f in all_fruits:
        if f.type == type:
           return f
    return None

Upvotes: 3

Views: 1983

Answers (2)

bigbounty
bigbounty

Reputation: 17368

You can use this method only if there are no duplicate types. You can use dictionaries for this.

d = {
"apple" : fruits('apple', 'red', 1.89, 5),
"pear" : fruits('pear', 'green', 2.89, 7),
"banana" : fruits('banana', 'yellow', 2.01, 10)
}

def take_fruit(type)
    return list(d[type])

Here, the dictionary stores type as key. This is faster in this way

Upvotes: 0

DeepSpace
DeepSpace

Reputation: 81614

You can use filter or list comprehension to make the code shorter, although not necessarily faster:

def take_fruit_listcomp(type, all_fruits):
    try:
        return [f for f in all_fruits if f.type == type][0]
    except IndexError:
        return None

def take_fruit_filter(type, all_fruits):
    try:
        # no need for list(..) if you use Python 2
        return list(filter(lambda f: f.type == type, all_fruits))[0]
    except IndexError:
        return None

Upvotes: 3

Related Questions