Python - Sort A List Of Dics By Value Of Dict`s Dict Value
I have a list that looks like this: persons = [{'id': 11, 'passport': {'id': 11, 'birth_info':{'date': 10/10/2016...}}},{'id': 22, 'passport': {'id': 22, 'birth_info':{'date': 11/1
Solution 1:
The function sorted()
provides the key
argument. One can define a callable which returns the key to compare the items:
sorted(persons, key=lambda x: x['passport']['birth_info']['date'])
The argument x is an item of the given list of persons.
If the dates are strings you could use the datetime
module:
sorted(persons, key=lambda x: datetime.datetime.strptime(x['passport']['birth_info']['date'], '%m/%d/%Y'))
Solution 2:
Try this
from datetime import datetime
print(sorted(persons, key=lambda x: datetime.strptime(x['passport']['birth_info']['date'], "%d/%m/%Y"))) #reverse=True for descending order.
Post a Comment for "Python - Sort A List Of Dics By Value Of Dict`s Dict Value"