python

Sort list and dictionary in python

Below is the description - how to sort different type of collections like list, dictionaries in python

#SORT DICTIONARY ITEMS
my_subjects = {
    "math": { "sub_code": "M001", "score": 60 },
    "physics": { "sub_code": "P001", "score": 40 },
    "chemistry": { "sub_code": "C001", "score": 50 },
    "english": { "sub_code": "E001", "score": 45 }
}

#SORT DATA ASCENDING ORDER
sorted_data_asc = sorted( my_subjects.items(), key = lambda x: x[1]['score'] )
print(dict(sorted_data_asc))

#SORT DATA DESCENDING ORDER
sorted_data_desc = sorted( my_subjects.items(), key = lambda x: x[1]['score'], reverse=True )
print(dict(sorted_data_desc))

#SORT A LIST OF DICTIONARIES
my_list = [
    {"name": "John", "score": 30},
    {"name": "Deep", "score": 10},
    {"name": "Mark", "score": 50}
]

list_asc = sorted(my_list, key = lambda i: i['score'])
print (list_asc)

list_desc = sorted(my_list, key = lambda i: i['score'], reverse=True)
print (list_desc)
Was this helpful?