Sorting a List of Dictionaries
When you have a list of dictionaries, you might want to organize them in sorted order with the help of a key.
Python: 3.0    Abhay Parashar    04 Jul 2021   0
Login to upvote
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
dict1 = [
    {"Name":"Karl",
     "Age":25},
     {"Name":"Lary",
     "Age":39},
     {"Name":"Nina",
     "Age":35}
]

## Using sort()
dict1.sort(key=lambda item: item.get("Age"))

# List sorting using itemgetter
from operator import itemgetter
f = itemgetter('Name')
dict1.sort(key=f)


# Iterable sorted function
dict1 = sorted(dict1, key=lambda item: item.get("Age"))

'''Output
[{'Age': 25, 'Name': 'Karl'},
 {'Age': 35, 'Name': 'Nina'},
 {'Age': 39, 'Name': 'Lary'}]
'''
Copy | Download as: .py file   PNG
Share on: FB   Twitter   LinkedIn   WA
©2021 - code108labs   Contributors   Hosted on DigitalOcean   Partner website: pythoncircle.com