"Mastering Python: Sorting List of Dictionaries by Key"

Sorting a List of Dictionaries in Python: A Comprehensive Guide

In Python, you can sort a list of dictionaries based on a specific key using the built-in `sorted()` function or the list's `sort()` method. This can be incredibly useful when you need to organize data based on a particular attribute. Let's dive into how you can achieve this with clear examples.

Using the `sorted()` function

The `sorted()` function returns a new sorted list from the elements of any sequence. It doesn't modify the original list. Here's how you can use it to sort a list of dictionaries:

```python # Sample list of dictionaries list_of_dicts = [ {'name': 'John', 'age': 25}, {'name': 'Jane', 'age': 30}, {'name': 'Jim', 'age': 22}, ] # Sort by 'age' key sorted_list = sorted(list_of_dicts, key=lambda x: x['age']) print(sorted_list) ```

In this example, the list is sorted based on the 'age' key in ascending order. If you want to sort in descending order, you can use the `reverse` parameter:

Python Sort Dictionary by Key and Value with Example
Python Sort Dictionary by Key and Value with Example

```python sorted_list = sorted(list_of_dicts, key=lambda x: x['age'], reverse=True) ```

Using the `sort()` method

The `sort()` method sorts the list in-place, meaning it modifies the original list. Here's how you can use it:

```python # Sort the original list in-place list_of_dicts.sort(key=lambda x: x['age']) ```

Again, to sort in descending order, use the `reverse` parameter:

```python list_of_dicts.sort(key=lambda x: x['age'], reverse=True) ```

Sorting by multiple keys

You can also sort by multiple keys. To do this, provide a tuple of keys to the `key` parameter. The list will be sorted first by the first key, then by the second key if the first keys are equal, and so on:

Python Collection Data Types | Lists, Tuples, Sets & Dictionaries Explained
Python Collection Data Types | Lists, Tuples, Sets & Dictionaries Explained

```python list_of_dicts.sort(key=lambda x: (x['age'], x['name'])) ```

Sorting with Custom Comparators

Sometimes, you might want to sort based on a custom comparator function. You can achieve this by providing a function to the `key` parameter that returns a value to sort by. Here's an example where we sort by the length of the 'name' key:

```python list_of_dicts.sort(key=lambda x: len(x['name'])) ```

Sorting with `itemgetter`

Python's `operator` module provides a function called `itemgetter` that can simplify sorting by a specific key. Here's how you can use it:

```python from operator import itemgetter list_of_dicts.sort(key=itemgetter('age')) ```

Using `itemgetter` can make your code more readable, especially when sorting by multiple keys:

the cover of collection data types in python, with an image of numbers and symbols
the cover of collection data types in python, with an image of numbers and symbols

```python list_of_dicts.sort(key=itemgetter('age', 'name')) ```

Sorting with `attrgetter`

Similarly, the `attrgetter` function from the `operator` module can be used to sort by attributes of objects. However, since we're working with dictionaries, `itemgetter` is more appropriate.

Sorting with `sorted()` and `itemgetter`

You can also use `itemgetter` with the `sorted()` function for a more explicit separation of sorting and original data:

```python from operator import itemgetter sorted_list = sorted(list_of_dicts, key=itemgetter('age')) ```

Conclusion

In this article, we've explored various ways to sort a list of dictionaries in Python. Whether you're using the `sorted()` function or the `sort()` method, and whether you're sorting by a single key or multiple keys, Python provides several options to suit your needs. Happy sorting!

All Important Python Functions for Beginners (Complete Cheat Sheet)
All Important Python Functions for Beginners (Complete Cheat Sheet)
Python Dictionaries Explained (With Real Examples)
Python Dictionaries Explained (With Real Examples)
Python List vs Dictionary – Made Easy For Beginners This tells viewers: ✔ It’s Python content ✔ It’s
Python List vs Dictionary – Made Easy For Beginners This tells viewers: ✔ It’s Python content ✔ It’s
Is Dictionary Mutable in Python
Is Dictionary Mutable in Python
Dictionaries in Python 💻
Dictionaries in Python 💻
PYTHON BASICS
PYTHON BASICS
python
python
an info sheet with the words important method in python, set list and keywords
an info sheet with the words important method in python, set list and keywords
Python Lists infographic for beginners
Python Lists infographic for beginners
10 Python Dictionary Methods Every Beginner Should Know (Cheat Sheet)
10 Python Dictionary Methods Every Beginner Should Know (Cheat Sheet)
Python List & Dictionary Master Sheet | One-Page Quick Revision for Placements (Save This!)
Python List & Dictionary Master Sheet | One-Page Quick Revision for Placements (Save This!)
Day 21/30 of learning python 📊📚  follow for more easy tech tips for beginners 💥💻🚀
Day 21/30 of learning python 📊📚 follow for more easy tech tips for beginners 💥💻🚀
Python dictionaries cheat sheet tutorial
Python dictionaries cheat sheet tutorial
Python Syntax Data Collections
Python Syntax Data Collections
an image of a computer screen with the words'multi - value dictionary in python '
an image of a computer screen with the words'multi - value dictionary in python '
Python Unit 4 Cheat Sheet 🐍 | Lists, Tuples, Dictionary & Set (AKTU)
Python Unit 4 Cheat Sheet 🐍 | Lists, Tuples, Dictionary & Set (AKTU)
Python Dictionary Methods
Python Dictionary Methods
Python list challenges cheat-sheet
Python list challenges cheat-sheet
a black screen with white text on it
a black screen with white text on it
Python list methods every developer should know.
Python list methods every developer should know.
Python Cheat Sheet for Beginners 2026 | Python Basics, Syntax, Loops, Functions & Variables
Python Cheat Sheet for Beginners 2026 | Python Basics, Syntax, Loops, Functions & Variables
Python Dictionary Methods 3
Python Dictionary Methods 3
Python Dictionary Methods Cheat Sheet (With Examples) | Python Quick Reference Guide
Python Dictionary Methods Cheat Sheet (With Examples) | Python Quick Reference Guide