Skip to content

Instantly share code, notes, and snippets.

@mschulz
Created September 25, 2024 01:33
Show Gist options
  • Save mschulz/bf8b61c014261ed6a75e952f0f69d1d0 to your computer and use it in GitHub Desktop.
Save mschulz/bf8b61c014261ed6a75e952f0f69d1d0 to your computer and use it in GitHub Desktop.
Sorting dict objects
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