Skip to main content

How to sort a dictionary by key in Python

How to sort a dictionary by key in Python.

Here's a detailed step-by-step tutorial on how to sort a dictionary by key in Python:

Step 1: Create a dictionary

First, you need to create a dictionary that you want to sort. A dictionary in Python is an unordered collection of key-value pairs. Here's an example dictionary:

my_dict = {'banana': 3, 'apple': 2, 'orange': 4}

Step 2: Convert the dictionary into a list of tuples

In order to sort the dictionary by key, you need to convert it into a list of tuples. Each tuple will consist of a key-value pair from the dictionary. You can use the items() method to achieve this. Here's how you can convert the dictionary into a list of tuples:

my_list = list(my_dict.items())

Step 3: Sort the list of tuples

Now that you have a list of tuples, you can sort it using the sorted() function. The sorted() function returns a new sorted list while leaving the original list unchanged. To sort the list of tuples by key, you can pass a lambda function as the key parameter to the sorted() function. The lambda function should return the first element of each tuple, which represents the key. Here's how you can sort the list of tuples:

sorted_list = sorted(my_list, key=lambda x: x[0])

Step 4: Convert the sorted list back into a dictionary

Once the list of tuples is sorted, you can convert it back into a dictionary if needed. You can use a dictionary comprehension to achieve this. Here's how you can convert the sorted list back into a dictionary:

sorted_dict = {key: value for key, value in sorted_list}

Step 5: Print the sorted dictionary

Finally, you can print the sorted dictionary to see the sorted key-value pairs. Here's an example:

print(sorted_dict)

The output will be:

{'apple': 2, 'banana': 3, 'orange': 4}

Full code example:

my_dict = {'banana': 3, 'apple': 2, 'orange': 4}
my_list = list(my_dict.items())
sorted_list = sorted(my_list, key=lambda x: x[0])
sorted_dict = {key: value for key, value in sorted_list}
print(sorted_dict)

That's it! You have successfully sorted a dictionary by key in Python.