Custom Sorting Python Dictionary




Here is a dictionary object holding student name as key and student information as value

>>> studentDb = { 'sark' : { 'country' : 'india', 'mark' : 99 }, 'jack' : { 'country' : 'US', 'mark' : 98 },'guns' : { 'country' :  'netherlands', 'mark' : 94 }, 'rakes' : { 'country' : 'india', 'mark' : 93 } }


Printing the student names and their details by iterating the studentDb dictionary

>>> for student, details in studentDb.iteritems():
...     print student, details
...
sark {'country': 'india', 'mark': 98}
rakes {'country': 'india', 'mark': 100}
jack {'country': 'US', 'mark': 94}
guns {'country': 'netherlands', 'mark': 99}
>>>


You may notice that the iteration not returned the student details in the same order, that's in the dictionary.

Dictionaries in Python are unordered. Here is a solution to sort python dictionary object in custom order.


Solution:


>>> studentDb_sorted = sorted(studentDb.items(), 
    key=lambda i: studentList.index(i[0]))


>>> for student, details in studentDb_sorted:
...     print student, details
... 
sark {'country': 'india', 'mark': 98}
jack {'country': 'US', 'mark': 94}
guns {'country': 'netherlands', 'mark': 99}
rakes {'country': 'india', 'mark': 100}


Output of the sorting method would return a list object with tuples. If you would like to have the output object as similar to dictionary, consider using the below method which uses OrderedDict

(or)

>>> from collections import OrderedDict

>>> sorted_db = OrderedDict(sorted(studentDb.items(), 
    key=lambda i: studentList.index(i[0])))          

>>> type(sorted_db)
<class 'collections.OrderedDict'>

>>> for student, details in sorted_db:
...     print student, details
... 
sark {'country': 'india', 'mark': 98}
jack {'country': 'US', 'mark': 94}
guns {'country': 'netherlands', 'mark': 99}
rakes {'country': 'india', 'mark': 100}





Post a Comment

0 Comments