Oz Bar-Shalom Oz Bar-Shalom - 16 days ago 4x
Python Question

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 ?


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