Created
September 25, 2024 01:33
-
-
Save mschulz/bf8b61c014261ed6a75e952f0f69d1d0 to your computer and use it in GitHub Desktop.
Sorting dict objects
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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'}] | |
''' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment