简体   繁体   中英

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/11/2016...}}}]

I need to sort the list of persons by their sub key of sub key - their birth_info date.

How should I do it ? Thanks

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'))

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM