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
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
marks.items()gives the pairs("Riya", 88),("Arjun", 72)and so on.sorted()normally compares pairs by their first item, the name, andkey=by_marktells it to compare the second item, the mark, instead.- 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. - The original dictionary is not changed, because
sorted()always returns something new.
Other ways to write it
Using a lambda, highest first
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
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.
Related programs
- Sort a Dictionary by Key
- Find the Key with the Maximum Value in a Dictionary
- Sort a List of Tuples by the Second Item
- Find Students Who Scored Above 75 Using a Dictionary
- Merge Two Dictionaries
- Check if a Key Exists in a Dictionary
- Create a Dictionary from Two Lists
- Remove a Key from a Dictionary
- Find the Sum of All Values in a Dictionary
All Python programs · CBSE class 12 practical file · Python exercises