DEV Community

Zander Bailey
Zander Bailey

Posted on

Getting Sorted Part 3: Python and Lambda Functions

Some functions can accept an entire second function as a parameter, which can be very useful, but if you only need a very simple function it can be a hassle to write out a whole separate function just so you can pass it as a parameter. It turns out there is an easier way to provide simple functions to a parameter: Lambda functions. Lambda functions have many uses, but today we’ll talk about how they are useful for sorting, First, let’s look at why we need to pass functions for sorting in the first place. Normally a function like sorted will sort strings by alphabetical order, unless we specify otherwise. The way we specify how we want the list sorted is with the key parameter. key accepts a function, and every item will be passed to the function individually, and return a value by which it will be sorted. Let’s see an example of this, say we want to sort a list of strings by length instead of alphabetically:

flowers = ['tulip', 'iris', 'primrose', 'violet']
sorted(flowers, key=len())
#returns: ['iris','tulip','violet','primrose'] 
Enter fullscreen mode Exit fullscreen mode

So by passing the len function as the key, it sorts by the length of the string. In the same way we can use many different functions to sort items in a list, and this is where Lamba functions become important. By using Lambda functions we can specify exactly how we want the list sorted. This become even more important when we try to sort more complex collection types. For example a list of tuples is something that comes up from time to time, and it can be useful to have it sorted. But even if one or more values in the tuple contain numbers or some other item we want to sort by, the normal sorting function does not see that information. So how do we get it to sort by something inside the tuple? We use a lambda function as the key. Say we have a list of tuples containing a persons name and their age, and we want to sort it by age:

ages = [('billy',16),('anna',17),('joe',15),('kelly',19)]
sorted(ages,key=lambda x: x[1])
#returns: [('joe',15),('billy',16),('anna',17),('kelly',19)]
Enter fullscreen mode Exit fullscreen mode

Alternatively we could sort this list alphabetically by name with a similar function. There is also a way to sort a dictionary. This is a little tricky since dictionaries are normally orderless, but there are some ways we can look at sorting them, mainly by key and by value. There are several ways to go about this, depending on what you want your output to be. Using our ages example again, if we only want the ages and we don’t care about the name, we can simply use the .values() method to get the values as a list and sort that. But if we want to retain all the information in dictionary, keys and values, we make use of lambda notation:

ages = {'billy':16,'anna':17,'joe':15,'kelly':19}
sorted(ages.items(),key=lambda x:x[1])
Enter fullscreen mode Exit fullscreen mode

.items() returns a list of all key-value pairs as tuples, and the lambda function tells it to sort by the second item in each tuple, i.e. the value. Alternatively if you want to sort by the key, just change lambda x:x[1] to lambda x:x[0]. We’re not quite done yet though, because now we have a list of tuples, instead of a dictionary. If that’s all you need, great. If you really want it as a dictionary, here’s how: combine with list comprehension, or in this case dictionary comprehension:

ages = {'billy':16,'anna':17,'joe':15,'kelly':19}
{k: v for k,v in sorted(ages.items(),key=lambda x:x[1])}
#[('joe', 15), ('billy', 16), ('anna', 17), ('kelly', 19)] ->  {‘joe': 15, 'billy': 16, 'anna': 17, 'kelly': 19}
Enter fullscreen mode Exit fullscreen mode

Now we have it back in sorted order, but as a dictionary. There are many other ways to sort collections, but hopefully this will get you started, and give you an idea of the kind of things you can do with sorting.

Top comments (1)

Collapse
 
rodrigovz profile image
Rodrigo

Hey, nice tutorial! There is a small mistake in the first block of code.
It should be:

flowers = ['tulip', 'iris', 'primrose', 'violet']
sorted(flowers, key=len)