In Python, the dictionary class doesn't have any provision to sort items in its object. Hence, some other data structure, such as the list has to be used to be able to perform sorting.
To begin with, our test data is following dictionary object having names and marks of students.
The dict
class has items() method that returns a view of list of tuples, each tuple having key and value of each pair in a dictionary.
markdict={"Tom":67, "Tina": 54, "Akbar": 87, "Kane": 43, "Divya":73}
marklist=list(markdict.items())
print(marklist)
[('Tom', 67), ('Tina', 54), ('Akbar', 87), ('Kane', 43), ('Divya', 73)]
The list allows its items to be rearranged in place. We can employ a simple bubble sort to arrange tuples according to the mark
component, as shown below.
markdict={"Tom":67, "Tina": 54, "Akbar": 87, "Kane": 43, "Divya":73}
l=len(marklist)
for i in range(l-1):
for j in range(i+1,l):
if marklist[i][1]>marklist[j][1]:
t=marklist[i]
marklist[i]=marklist[j]
marklist[j]=t
sortdict=dict(marklist)
print(sortdict)
{'Kane': 43, 'Tina': 54, 'Tom': 67, 'Divya': 73, 'Akbar': 87}
Using sorted() Method
Understandably, this solution is slow and inefficient. Python's built-in function library has a better solution for this in the form of the sorted() function.
markdict = {"Tom":67, "Tina": 54, "Akbar": 87, "Kane": 43, "Divya":73}
marklist = sorted(markdict.items(), key=lambda x:x[1])
sortdict = dict(marklist)
print(sortdict)
{'Kane': 43, 'Tina': 54, 'Tushar': 67, 'Divya': 73, 'Amar': 87}
Another option is to use the itemgetter()
function as defined in the operator
module bundled with Python's standard library.
The itemgetter()
function returns a callable object from its operand.
import operator
markdict = {"Tom":67, "Tina": 54, "Akbar": 87, "Kane": 43, "Divya":73}
marklist= sorted(markdict.items(), key=operator.itemgetter(1))
sortdict=dict(marklist)
print(sortdict)
{'Kane': 43, 'Tina': 54, 'Tushar': 67, 'Divya': 73, 'Amar': 87}
Finally, we shall use the dict.items()
method along with the sorted()
function to first obtain (marks, name)
tuples and then reconstruct dictionary in a sorted order of marks
.
markdict = {"Tom":67, "Tina": 54, "Akbar": 87, "Kane": 43, "Divya":73}
marklist=sorted((value, key) for (key,value) in markdict.items())
sortdict=dict([(k,v) for v,k in marklist])
print(sortdict)
{'Kane': 43, 'Tina': 54, 'Tushar': 67, 'Divya': 73, 'Amar': 87}