Sort List or Dictionary by two keys in Python

featured Image

In this article, we will learn how to sort a list or dictionary using multiple keys in Python.

Sorting a list or dictionary can be easily done using the sort() method and sorted() function in Python.

However, if you want to sort a list or dictionary by multiple elements, let’s say two keys then the easiest way is to use the key parameter and tuple the keys that we want to sort.

Let’s see some examples of sorting by two keys in Python.

Sort list of dictionaries by multiple keys

To sort a list of dictionaries we can use the sort() method in Python.

Now to sort the list of objects by two keys:

  1. We have to use the key argument in sort() method and pass the lambda function.

Note: The key is an optional argument that is used to sort items by different criteria. It can take functions to determine the sorting of items.

  1. Next, pass the tuple of the keys that we want to sort by to the sorting lambda expression.

Let’s see an example to sort a list of employee dictionaries by two keys: name and salary using sort() function.

employee_list = [
        {'name': 'Jack','salary':2000},
        {'name': 'Danny','salary':1000},
        {'name': 'Adam','salary':1500},
        {'name': 'Bob','salary':1000},
    ]

employee_list.sort(key= lambda x: (x["salary"],x["name"]))
print(employee_list)

Output:

[{'name': 'Bob', 'salary': 1000}, {'name': 'Danny', 'salary': 1000}, {'name': 'Adam', 'salary': 1500}, {'name': 'Jack', 'salary': 2000}]

In the above example, we have sorted the list of employee dictionaries by two keys: first by salary and second by the name key.

Sort List of Tuples by two keys in Python

If you have a list of tuples and you want to sort the values using two keys in Python, then we can use the sort() method and use a lambda function with the tuple to sort.

So to sort a list of tuples by two keys:

  1. Use the sort() method on the list.
  2. Use the key parameter and pass the lambda function.
  3. Now select the values in the tuple you want to sort by using its specific indices. Here we will sort by the first two elements, so the index are k[0] and k[1].
tuple_list = [('a','c','b'),('b','c','a'),('a','b','d'),('c','a','b')]

tuple_list.sort(key=lambda k: (k[0],k[1]))

print(tuple_list)

Output:

[('a', 'b', 'd'), ('a', 'c', 'b'), ('b', 'c', 'a'), ('c', 'a', 'b')]

This way you can sort tuples by multiple elements in python.

Sort a dictionary by two keys in Python

To sort a dictionary by two keys we have to use the sorted() function and pass the lambda function to the key parameter.

emp_list = {'Jack':2000, 'Danny': 1000, 'Adam': 1500, 'Bob': 1000}

sorted_list = sorted(emp_list, key= lambda x: (emp_list[x],x))
print(sorted_list)

Output:

['Bob', 'Danny', 'Adam', 'Jack']

It has printed out the list based on the salary and the name keys.

If you want to print out the salary along with the name in the output, we have to print out the results in tuple.

We can use the items() method of the dictionary object that returns the (key, value) tuple pair.

emp_list = {'Jack':2000, 'Danny': 1000, 'Adam': 1500, 'Bob': 1000}

sorted_list = sorted(emp_list.items(), key= lambda x: (x[1],x[0]))
print(sorted_list)

Output:

[('Bob', 1000), ('Danny', 1000), ('Adam', 1500), ('Jack', 2000)]

Here, the emp_list.items() returns the tuple with the key and value.

Next, we sorted the dictionary using two keys: salary and name of the employee.

Conclusion:

Here, we have learned how to sort a list, dictionary, and tuple by multiple keys using the list’s sort() method and the sorted() function in python.


Other Articles You’ll Also Like:

Reverse a range in python

Merge two dictionaries together using python (3 ways)

Python | Delete an Element (key) From a Python Dictionary

Get the Index or Position of Item in List in Python

How to split a list into multiple list using python

Remove Duplicates from List in Python

Prepend List in Python

Python – Insert an element at specific index in a list

Python – Check if list is empty or not

Remove the Last N element from a List in Python

Related Posts

merge json files in python

How to merge JSON files in python

JSON (JavaScript Object Notation) is a data format used for storing, transferring, and visualizing data. Its simple structure of key:value pairs and array data types makes JSON an easy and…

Read more
Install python pip in ubuntu

How to Install Pip(pip3) in Ubuntu Linux 22.04

Pip is a package manager for Python that allows you to install and manage additional Python packages that are not part of the Python standard library. Pip makes it easy…

Read more
featured Image

How to Write If-Else Statements in One Line in Python

If-else statements are a fundamental concept in Python and other programming languages. They allow you to execute different blocks of code based on whether a condition is true or false….

Read more

Leave a Reply

Your email address will not be published. Required fields are marked *