Sort List By Dict Values – Python [One-Liner]


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)
# :param iterable: an iterable object (such as a list!)
# :param key: the function that will instruct how to sort
# :param reverse: if you want to make the sort order descending set to True

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.

Ryan

Author of scripteverything.com, Ryan has been dabbling in code since the late '90s when he cut his teeth by exploring VBA in Excel when trying to do something more. Having his eyes opened with the potential of automating repetitive tasks, he expanded to Python and then moved over to scripting languages such as HTML, CSS, Javascript and PHP. When he is not behind a screen, Ryan enjoys a good bush walk with the family during the cooler months, and going with them to the beach during the warmer months.

Recent Posts