Oz Bar-Shalom Oz Bar-Shalom - 1 year ago 83
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 ?

Answer Source

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'))
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download