Moving on from my previous post where I was sorting a list after the second element on, I now needed to sort the list of dictionaries by their values.
If I assume the following data set:
>>> data = [{ 'Surname': 'Jones', 'Address': '1 Smith Way', '2020-Census': 5, '2016-Census': 3, '2012-Census': 2}, {'Surname': 'Smith', 'Address': '2 Smith Way', '2020-Census': 2, '2016-Census': 2, '2012-Census': 2}, {'Surname': 'Doe', 'Address': '3 Smith Way', '2020-Census': 5, '2016-Census': 4, '2012-Census': 4}]
How would I go about sorting this data if I needed the List
to be sorted by the Dict
value represented by the key
name Surname
?
Thankfully the sorted()
function comes in handy here, the parameters for the function are as follows:
sorted(iterable, key, reverse)
The first parameter iterable
takes an iterable object such as a list, or even a dictionary (more on this later). The second parameter key
takes a function or key value that instructs how to sort. And finally, the reverse
parameter takes a boolean value on whether the sort is in descending order, by default this value is False
.
The great thing about the sorted
function is that it doesn’t mutate the list passed in at the first parameter. Therefore, we could achieve the desired result of sorting by the key name Surname
by simply writing the following:
>>> sorted_data = sorted(data, key=lambda x:x['Surname'])
>>> print(sorted_data)
[{'Surname': 'Doe', 'Address': '3 Smith Way', '2020-Census': 5, '2016-Census': 4, '2012-Census': 4},
{'Surname': 'Jones', 'Address': '1 Smith Way', '2020-Census': 5, '2016-Census': 3, '2012-Census': 2},
{'Surname': 'Smith', 'Address': '2 Smith Way', '2020-Census': 2, '2016-Census': 2, '2012-Census': 2}]
The function used is a simple one-liner that performs the necessary task and uses a lambda
function to get the job done.
What is a lambda function?
A lambda function is a function that simply performs operations without needing to be defined by a name.
In our working example, the lambda function accepts one parameter which we’ve labelled as x
and the value being passed in is each Dict
item from the List
.
As the value is each Dict
passed in we can then set the key
that will be used to be the ordering condition, which we set as x['Surname']
.
Summary
Sorting our list of dictionaries in Python can easily be achieved using the sorted
function. By passing in our list as the first parameter, and using a lambda
function as the key
parameter we can achieve the desired result of getting a sorted list of dictionaries in Python in one line.