Editor

Python Program to Sort a Dictionary by Value

Beginner · Dictionaries

A dictionary pairs keys with values, and sorting by value puts the pairs in order of their values, for example students in order of their marks. Python sorts the (key, value) pairs and builds a new dictionary from them.

Program

sort_dictionary_by_value.py
marks = {"Riya": 88, "Arjun": 72, "Meera": 95, "Kabir": 64}
def by_mark(pair):
return pair[1] # pair is (name, mark), so pair[1] is the mark
pairs = sorted(marks.items(), key=by_mark)
lowest_first = dict(pairs)
print("Original: ", marks)
print("Sorted pairs:", pairs)
print("Lowest first:", lowest_first)
Output
Original:     {'Riya': 88, 'Arjun': 72, 'Meera': 95, 'Kabir': 64}
Sorted pairs: [('Kabir', 64), ('Arjun', 72), ('Riya', 88), ('Meera', 95)]
Lowest first: {'Kabir': 64, 'Arjun': 72, 'Riya': 88, 'Meera': 95}

How it works

  1. marks.items() gives the pairs ("Riya", 88), ("Arjun", 72) and so on.
  2. sorted() normally compares pairs by their first item, the name, and key=by_mark tells it to compare the second item, the mark, instead.
  3. The result is a list of pairs from the lowest mark to the highest, and dict() turns it back into a dictionary that keeps that order.
  4. The original dictionary is not changed, because sorted() always returns something new.

Other ways to write it

Using a lambda, highest first

Using a lambda, highest first
marks = {"Riya": 88, "Arjun": 72, "Meera": 95, "Kabir": 64}
highest_first = dict(sorted(marks.items(), key=lambda pair: pair[1], reverse=True))
print("Highest first:", highest_first)
Output
Highest first: {'Meera': 95, 'Riya': 88, 'Arjun': 72, 'Kabir': 64}

lambda pair: pair[1] is a one-line function that does the same job as by_mark, and reverse=True puts the biggest value first. This is the form you will see most often.

Printing a rank list

Printing a rank list
marks = {"Riya": 88, "Arjun": 72, "Meera": 95, "Kabir": 64}
ranked = sorted(marks, key=marks.get, reverse=True) # names, best first
for rank, name in enumerate(ranked, start=1):
print(f"{rank}. {name:6} {marks[name]}")
Output
1. Meera  95
2. Riya   88
3. Arjun  72
4. Kabir  64

Sorting the dictionary itself sorts its keys, and key=marks.get orders those keys by their values. enumerate(..., start=1) numbers the ranks from 1.

Try it yourself

Add two students with the same mark and check how sorted() orders them.

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