
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort a Dictionary in Python by Keys
Python allows dictionaries to be sorted using the built-in sorted() function. Although dictionaries in Python 3.7+ preserve insertion order, we can still create a new dictionary sorted by its keys using various methods.
In this article, we will explore different ways to sort a dictionary in Python by its keys.
Using sorted() with a for Loop
We can use the sorted() function on the dictionary keys and then iterate through them to build a new dictionary in key order.
Example
Following is an example, which shows how to sort a dictionary in Python using the sorted() function -
dictionary = { 'b': 2, 'a': 1, 'd': 4, 'c': 3 } # Creating a new dictionary by sorting keys sorted_dict = {} for key in sorted(dictionary.keys()): sorted_dict[key] = dictionary[key] print(sorted_dict)
Following is the output of the above program -
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
Using Dictionary Comprehension
Python provides a concise way to sort dictionaries using dictionary comprehension. The keys are sorted and values are assigned in a single line.
Example
Here is an example that uses dictionary comprehension to sort the dictionary using Python -
dictionary = { 'b': 2, 'a': 1, 'd': 4, 'c': 3 } # Sorting dictionary by keys using comprehension sorted_dict = {key: dictionary[key] for key in sorted(dictionary)} print(sorted_dict)
Below is the output of the above program -
{'a': 1, 'b': 2, 'c': 3, 'd': 4}
Using collections.OrderedDict
The OrderedDict() function from the collections module remembers the order in which keys are inserted. It is useful when order is important.
Example
Following is an example in which we use the OrderedDict()function of the collections module to sort the dictionary keys -
from collections import OrderedDict dictionary = { 'b': 2, 'a': 1, 'd': 4, 'c': 3 } # Sorting dictionary by keys using OrderedDict sorted_dict = OrderedDict(sorted(dictionary.items())) print(sorted_dict)
Here is the output of the above program -
OrderedDict([('a', 1), ('b', 2), ('c', 3), ('d', 4)])