How to sort a dictionary based on keys in Python?

Python – Sort Dictionary based on Keys

As of Python version 3.7, dictionaries are ordered, and we can sort a dictionary based on keys.

To sort a dictionary based on keys in Python, you can use built-in function sorted(). Pass the dictionary items dict.items() for the first argument, and a lambda function that returns key from the item for the named argument key.

sorted() function returns a list of tuples, and to convert this to a dictionary of key-value pairs, we can use dict() function.


The syntax to sort the key-value pairs in a dictionary dict1 based on the keys is

dict(sorted(dict1.items(), key=lambda item: item[0]))

item[0] returns key from the item (key-value pair).


In the following example, we take a dictionary with some key-value pairs. We will use sorted() and dict() built-in functions to sort the items in dictionary based on keys.

Python Program

dict1 = {
    "key3": 30,
    "key1": 10,
    "key4": 40,
    "key2": 20}

sorted_dict = dict(sorted(dict1.items(), key=lambda item: item[0]))
Run Code Copy


{'key1': 10, 'key2': 20, 'key3': 30, 'key4': 40}


In this tutorial, we learned how dictionaries can be sorted based on the keys using sorted() built-in function, with examples.

Related Tutorials

Code copied to clipboard successfully 👍