[python]list comprehension and lambda function

The below is a code sample without using list comprehension or lambda function just a straight forward to enumerate through items in a list of dictionary to try to find a match in name.

list_of_dict = [
    {
        'name': 'John',
        'age': 20
    },
    {
        'name': 'Tom',
        'age': 22
    },
    {
        'name': 'Kelvin',
        'age': 21
    }
]

def search(name):
    for item in list_of_dict:
        if item['name'] == name:
            return name
        return f"{name} is not found.."

To test the above, print(search('John'))
result is : John
another test, print(search('cyrus'))
result is : cyrus is not found..

Lambda function
Use lambda function to achieve the same thing:

list_of_dict = [
    {
        'name': 'John',
        'age': 20
    },
    {
        'name': 'Tom',
        'age': 22
    },
    {
        'name': 'Kelvin',
        'age': 21
    }
]

def search(name):
    result = next(filter(lambda x: x['name'] == name, list_of_dict), None)
    return result['name'] if result else f"{name} is not found"

The lambda function is an unnamed function that uses to do simple task, some sort like an ad hoc function.
filter(lambda x: x['name'] == name, list_of_dict))
The filter() takes in two arguments: a function and iterable which can be a list. This one liner code is similar to below:

for x in list_of_dict:
if x['name'] == name:
x

The filter() itself returns an object, it is usually use in conjunction with another function such as next() or list()
The next() function returns the result on the first match, if not found the default None will be returned.

List comprehension
Another way of doing is to use list comprehension, but the return data type will be a list.

list_of_dict = [
    {
        'name': 'John',
        'age': 20
    },
    {
        'name': 'Tom',
        'age': 22
    },
    {
        'name': 'Kelvin',
        'age': 21
    }
]

def search(name):
    result = [item['name'] for item in list_of_dict if item['name'] == name]
    return result if result else f"{name} is not found.."

print(search('John')) the result is ['John'] the result is the same as the first example if the name is not found.

Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s