Editor

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

sort_dictionary_by_key.py
capitals = {
"Kerala": "Thiruvananthapuram",
"Assam": "Dispur",
"Punjab": "Chandigarh",
"Goa": "Panaji",
}
sorted_capitals = {}
for state in sorted(capitals): # sorted() on a dictionary sorts its keys
sorted_capitals[state] = capitals[state]
print("Original order:", list(capitals))
print("Sorted by state:")
for state, capital in sorted_capitals.items():
print(f" {state:7} {capital}")
Output
Original order: ['Kerala', 'Assam', 'Punjab', 'Goa']
Sorted by state:
  Assam   Dispur
  Goa     Panaji
  Kerala  Thiruvananthapuram
  Punjab  Chandigarh

How it works

  1. sorted(capitals) returns the keys of the dictionary as a sorted list: Assam, Goa, Kerala, Punjab.
  2. The loop adds each key, with its value, to a new dictionary in that sorted order.
  3. Dictionaries remember the order keys were added in, so the new dictionary stays sorted when you print it or loop over it.
  4. 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())

Using dict(sorted())
capitals = {"Kerala": "Thiruvananthapuram", "Assam": "Dispur", "Goa": "Panaji"}
print("A to Z:", dict(sorted(capitals.items())))
print("Z to A:", dict(sorted(capitals.items(), reverse=True)))
Output
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

Number keys and mixed case
roll_numbers = {12: "Asha", 3: "Ravi", 7: "Neha"}
print("By roll number:", dict(sorted(roll_numbers.items())))
fruits = {"banana": 12, "Cherry": 7, "apple": 30}
print("Plain sort: ", dict(sorted(fruits.items())))
print("Ignoring case:", dict(sorted(fruits.items(), key=lambda pair: pair[0].lower())))
Output
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.

All Python programs · CBSE class 12 practical file · Python exercises