Python Program to Sort a Dictionary by Key
Beginner · Dictionaries
Sorting a dictionary by key puts its entries in order of their keys, such as names from A to Z or roll numbers from smallest to largest. A dictionary keeps the order its keys were added in, so the program builds a new one in sorted order.
Program
Original order: ['Kerala', 'Assam', 'Punjab', 'Goa'] Sorted by state: Assam Dispur Goa Panaji Kerala Thiruvananthapuram Punjab Chandigarh
How it works
sorted(capitals)returns the keys of the dictionary as a sorted list: Assam, Goa, Kerala, Punjab.- The loop adds each key, with its value, to a new dictionary in that sorted order.
- Dictionaries remember the order keys were added in, so the new dictionary stays sorted when you print it or loop over it.
- Text keys sort alphabetically and number keys sort by size, but mixing the two in one dictionary makes
sorted()raise a TypeError.
Other ways to write it
Using dict(sorted())
A to Z: {'Assam': 'Dispur', 'Goa': 'Panaji', 'Kerala': 'Thiruvananthapuram'}
Z to A: {'Kerala': 'Thiruvananthapuram', 'Goa': 'Panaji', 'Assam': 'Dispur'}Sorting items() compares the pairs by their first item, the key, so dict(sorted(...)) does the whole job in one line.
Number keys and mixed case
By roll number: {3: 'Ravi', 7: 'Neha', 12: 'Asha'}
Plain sort: {'Cherry': 7, 'apple': 30, 'banana': 12}
Ignoring case: {'apple': 30, 'banana': 12, 'Cherry': 7}Number keys sort by size. Capital letters sort before small ones, so "Cherry" comes first in a plain sort, and comparing pair[0].lower() ignores case.
Try it yourself
Add your own state and its capital to the dictionary and run the program again.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
- Sort a Dictionary by Value
- Merge Two Dictionaries
- Check if a Key Exists in a Dictionary
- Find Students Who Scored Above 75 Using a Dictionary
- Create a Dictionary from Two Lists
- Remove a Key from a Dictionary
- Find the Sum of All Values in a Dictionary
- Find the Key with the Maximum Value in a Dictionary
- Make a Simple Phone Book
All Python programs · CBSE class 12 practical file · Python exercises