Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Python – How to Sort a List of Dictionaries?

#1
Python – How to Sort a List of Dictionaries?

In this article, you’ll learn the ins and outs of the sorting function in Python. In particular, you’re going to learn how to sort a list of dictionaries in all possible variations. [1] So let’s get started!



How to Sort a List of Dictionaries …

… By Value?


Problem: Given a list of dictionaries. Each dictionary consists of multiple (key, value) pairs. You want to sort them by value of a particular dictionary key (attribute). How do you sort this dictionary?

Minimal Example: Consider the following example where you want to sort a list of salary dictionaries by value of the key 'Alice'.

salaries = [{'Alice': 100000, 'Bob': 24000}, {'Alice': 121000, 'Bob': 48000}, {'Alice': 12000, 'Bob': 66000}] sorted_salaries = # ... Sorting Magic Here ... print(sorted_salaries)

The output should look like this where the salary of Alice determines the order of the dictionaries:

[{'Alice': 12000, 'Bob': 66000},
{'Alice': 100000, 'Bob': 24000},
{'Alice': 121000, 'Bob': 48000}]

Solution: You have two main ways to do this—both are based on defining the key function of Python’s sorting methods. The key function maps each list element (in our case a dictionary) to a single value that can be used as the basis of comparison.

  • Use a lambda function as key function to sort the list of dictionaries.
  • Use the itemgetter function as key function to sort the list of dictionaries.

Here’s the code of the first option using a lambda function that returns the value of the key 'Alice' from each dictionary:

# Create the dictionary of Bob's and Alice's salary data
salaries = [{'Alice': 100000, 'Bob': 24000}, {'Alice': 121000, 'Bob': 48000}, {'Alice': 12000, 'Bob': 66000}] # Use the sorted() function with key argument to create a new dic.
# Each dictionary list element is "reduced" to the value stored for key 'Alice'
sorted_salaries = sorted(salaries, key=lambda d: d['Alice']) # Print everything to the shell
print(sorted_salaries)

The output is the sorted dictionary. Note that the first dictionary has the smallest salary of Alice and the third dictionary has the largest salary of Alice.

[{'Alice': 12000, 'Bob': 66000}, {'Alice': 100000, 'Bob': 24000}, {'Alice': 121000, 'Bob': 48000}]

Try It Yourself:

You’ll learn about the second way below (where you use the itemgetter function from the operator module).

Related articles on the Finxter blog:

… Using Itemgetter?


Same Problem: Given a list of dictionaries. Each dictionary consists of multiple (key, value) pairs. How to sort them by value of a particular dictionary key (attribute)?

Minimal Example: Consider again the following example where you want to sort a list of salary dictionaries by value of the key 'Alice'.

salaries = [{'Alice': 100000, 'Bob': 24000}, {'Alice': 121000, 'Bob': 48000}, {'Alice': 12000, 'Bob': 66000}] sorted_salaries = # ... Sorting Magic Here ... print(sorted_salaries)

The output should look like this where the salary of Alice determines the order of the dictionaries:

[{'Alice': 12000, 'Bob': 66000},
{'Alice': 100000, 'Bob': 24000},
{'Alice': 121000, 'Bob': 48000}]

Solution: Again, you’re going to define a key function. But instead of creating it yourself with the lambda keyword, you’re going to use an existing one. In particular, you’ll use the itemgetter function from the operator module to sort the list of dictionaries.

Here’s the code of the first option using a lambda function that returns the value of the key 'Alice' from each dictionary:

# Import the itemgetter function from the operator module
from operator import itemgetter # Create the dictionary of Bob's and Alice's salary data
salaries = [{'Alice': 100000, 'Bob': 24000}, {'Alice': 121000, 'Bob': 48000}, {'Alice': 12000, 'Bob': 66000}] # Use the sorted() function with key argument to create a new dic.
# Each dictionary list element is "reduced" to the value stored for key 'Alice'
sorted_salaries = sorted(salaries, key=itemgetter('Alice')) # Print everything to the shell
print(sorted_salaries)

The output is the sorted dictionary. Note that the first dictionary has the smallest salary of Alice and the third dictionary has the largest salary of Alice.

[{'Alice': 12000, 'Bob': 66000}, {'Alice': 100000, 'Bob': 24000}, {'Alice': 121000, 'Bob': 48000}]

Now, you know how to sort a list of dictionaries by value. But what if you want to sort by key?

… By Key?


Problem: Given a list of dictionaries. Each dictionary consists of multiple (key, value) pairs. How to sort them by a particular key (attribute)?

Solution: It doesn’t make sense. If you assume that all dictionaries have that same particular key, you cannot really sort because all dictionaries have the same key. If there’s no tie-breaker, it’s impossible to do. But even if there’s a tie-breaker (e.g. the value associated to the key), it doesn’t make sense because you could have sorted by value in the first place.

… By Multiple Keys?


Problem: Given a list of dictionaries. How do you sort by multiple key value pairs?

Minimal Example: Consider the following example where you want to sort a list of database entries (e.g. each stored as a dictionary) by value of the key 'username'. If the 'username' is the same, you use the 'joined' value as a tiebreaker. If the 'joined' date is the same, you use the 'age' as a tie breaker.

db = [{'username': 'Alice', 'joined': 2020, 'age': 23}, {'username': 'Bob', 'joined': 2018, 'age': 19}, {'username': 'Alice', 'joined': 2020, 'age': 31}] sorted_salaries = # ... Sorting Magic Here ... print(sorted_salaries)

The output should look like this where the salary of Alice determines the order of the dictionaries:

[{'username': 'Alice', 'joined': 2020, 'age': 23}, {'username': 'Alice', 'joined': 2020, 'age': 31}, {'username': 'Bob', 'joined': 2018, 'age': 19}]

Solution: You’re going to define a key function with the lambda keyword. But instead of returning a single value to a given key, you return a tuple—one entry per value that should be considered. For example, the database entry {'username': 'Alice', 'joined': 2020, 'age': 23} is mapped to ('Alice', 2020, 23). This ensures that two tuples that have the same first tuple value will still be sorted correctly by using the second tuple value as a tiebreaker.

Here’s the code:

# Create the dictionary of user entries in your database
db = [{'username': 'Alice', 'joined': 2020, 'age': 23}, {'username': 'Bob', 'joined': 2018, 'age': 19}, {'username': 'Alice', 'joined': 2020, 'age': 31}] # Use the sorted() function with key argument to create a new list.
# Each dictionary list element is "reduced" to the tuple of values.
db_sorted = sorted(db, key=lambda row: (row['username'], row['joined'], row['age'])) # Print everything to the shell
print(db_sorted)

The output is the sorted dictionary. Note that the first dictionary has the smallest salary of Alice and the third dictionary has the largest salary of Alice.

[{'username': 'Alice', 'joined': 2020, 'age': 23}, {'username': 'Alice', 'joined': 2020, 'age': 31}, {'username': 'Bob', 'joined': 2018, 'age': 19}]

In this example, the dictionary value for the key ‘joined’ was an integer number. But what if it’s a date?

… By Date?


Problem: Given a list of dictionaries. How do you sort the list of dictionaries by date?

Minimal Example: Consider the following example where you want to sort a list of database entries (e.g. each stored as a dictionary) by value of the key 'joined' that is from type date or timedate.

db = [{'username': 'Alice', 'joined': '2019-03-02', 'age': 23}, {'username': 'Bob', 'joined': '2020-08-08', 'age': 19}, {'username': 'Alice', 'joined': '2019-03-04', 'age': 31}] db_sorted = # ... sorting magic here ... print(db_sorted)

The output should look like this where the salary of Alice determines the order of the dictionaries:

[{'username': 'Alice', 'joined': '2019-03-02', 'age': 23}, {'username': 'Alice', 'joined': '2019-03-04', 'age': 31}, {'username': 'Bob', 'joined': '2020-08-08', 'age': 19}]

Solution: Define a key function with the lambda keyword. Simply return the string value for the key 'joined' for a given dictionary. This return value is then used to sort the dictionaries in the list.

As the join dates are given as strings in the form year-month-day (e.g. '2020-08-08'), the default alphabetical sort will also lead to a sorted overall list of dictionaries: the dictionary row with the earliest join date will be the first in the resulting list.

Here’s the code:

# Create the dictionary of user entries in your database
db = [{'username': 'Alice', 'joined': '2019-03-02', 'age': 23}, {'username': 'Bob', 'joined': '2020-08-08', 'age': 19}, {'username': 'Alice', 'joined': '2019-03-04', 'age': 31}] # Use the sorted() function with key argument to create a new list.
# Each dictionary list element is "reduced" to the join date.
db_sorted = sorted(db, key=lambda row: row['joined']) # Print everything to the shell
print(db_sorted)

The output is the sorted dictionary. Note that the first dictionary has the earliest and the third dictionary has the latest join date.

[{'username': 'Alice', 'joined': '2019-03-02', 'age': 23}, {'username': 'Alice', 'joined': '2019-03-04', 'age': 31}, {'username': 'Bob', 'joined': '2020-08-08', 'age': 19}]

You can use a similar method if the dictionary values are of format datetime as they are also comparable with default comparison operators >, <, >=, <=, and ==. [2]

… In Descending Order?


Problem: The default ordering of any Python list sort routine (sorted() and list.sort()) is in ascending order. This also holds if you sort a list of dictionaries. How can you sort in descending order?

Solution: If you want to sort in descending order, you can do one of the following:

  • Use slicing to reverse the sorted list.
  • Use the reverse=True argument of the sorted() or list.sort() methods.

Both ways are equivalent. Have a look at the previous example first using the reverse argument:

# Create the dictionary of user entries in your database
db = [{'username': 'Alice', 'joined': '2019-03-02', 'age': 23}, {'username': 'Bob', 'joined': '2020-08-08', 'age': 19}, {'username': 'Alice', 'joined': '2019-03-04', 'age': 31}] # Use the sorted() function with key argument to create a new list.
# Each dictionary list element is "reduced" to the join date.
db_sorted = sorted(db, key=lambda row: row['joined'], reverse=True) # Print everything to the shell
print(db_sorted)

Output:

[{'username': 'Bob', 'joined': '2020-08-08', 'age': 19}, {'username': 'Alice', 'joined': '2019-03-04', 'age': 31}, {'username': 'Alice', 'joined': '2019-03-02', 'age': 23}]

And second using slicing with negative step size (without the reverse argument):

# Create the dictionary of user entries in your database
db = [{'username': 'Alice', 'joined': '2019-03-02', 'age': 23}, {'username': 'Bob', 'joined': '2020-08-08', 'age': 19}, {'username': 'Alice', 'joined': '2019-03-04', 'age': 31}] # Use the sorted() function with key argument to create a new list.
# Each dictionary list element is "reduced" to the join date.
db_sorted = sorted(db, key=lambda row: row['joined'])[::-1] # Print everything to the shell
print(db_sorted)

Same output:

[{'username': 'Bob', 'joined': '2020-08-08', 'age': 19}, {'username': 'Alice', 'joined': '2019-03-04', 'age': 31}, {'username': 'Alice', 'joined': '2019-03-02', 'age': 23}]

… in Ascending Order?


The default ordering of any Python list sort routine (sorted() and list.sort()) is in ascending order. This also holds if you sort a list of dictionaries.

Where to Go From Here


In this article, you’ve learned how to sort a list of dictionaries. In summary, use the sorted() method with a key function as argument. This gives you the flexibility to customize how exactly you want to sort the dictionary—just map each dictionary to a comparable value.

I’ve realized that professional coders tend to use dictionaries more often than beginners due to their superior understanding of the benefits of dictionaries. If you want to learn about those, check out my in-depth tutorial of Python dictionaries.

If you want to stop learning and start earning with Python, check out my free webinar “How to Become a Python Freelance Developer?”. It’s a great way of starting your thriving coding business online.

“[Webinar] How to Become a Python Freelance Developer?”



https://www.sickgaming.net/blog/2020/04/...tionaries/
Reply



Forum Jump:


Users browsing this thread:
1 Guest(s)

[-]
Discord

[-]
Active Threads
News - Stardew Valley’s Latest 1.5.5 Upd...
Last Post: xSicKxBot
Today 07:10 AM
» Replies: 0
» Views: 1
News - Hood: Outlaws & Legends Season 2 ...
Last Post: xSicKxBot
Today 07:09 AM
» Replies: 0
» Views: 0
(Indie Deal) RE8, Frontier, Slitherine, ...
Last Post: xSicKxBot
Today 05:00 AM
» Replies: 0
» Views: 6
Microsoft - Inclusion for all this Inter...
Last Post: xSicKxBot
Today 02:39 AM
» Replies: 0
» Views: 5
News - .hack//G.U. Last Recode Is Coming...
Last Post: xSicKxBot
Today 02:39 AM
» Replies: 0
» Views: 3
News - A New Peacemaker TV Show Trailer ...
Last Post: xSicKxBot
Today 02:39 AM
» Replies: 0
» Views: 3
(Indie Deal) 2K, SNK, Ziggurat & Graffit...
Last Post: xSicKxBot
Yesterday 11:12 PM
» Replies: 0
» Views: 11
News - George Clooney Reveals Why He Tur...
Last Post: xSicKxBot
Yesterday 08:39 PM
» Replies: 0
» Views: 9
(Indie Deal) 2K, SNK, Ziggurat & Graffit...
Last Post: xSicKxBot
Yesterday 05:39 PM
» Replies: 0
» Views: 10
Microsoft - Fund manager RFP opens for M...
Last Post: xSicKxBot
Yesterday 05:39 PM
» Replies: 0
» Views: 3

[-]
Twitter

[-]
Sponsored
Get the Deal of the Week at RefurBees.com



Discord Server © SickGaming.net 2012-2021