Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sort List of Tuples by Date element

I need the oldest people be first on the list, here is the example of the format i have to sort:

List =[ ('John', '12345', '1972-02-08'),
('Sara', '12345', '1977-07-01'),  
('Mario', '12345', '1971-06-13') ,   
('Lucas', '12345', '1967-04-27'),
('Kiara', '12345', '1973-02-15')]

Im new on python so i have some doubts on this. ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎ ‎

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use sort(), sorted(), or datetime:

from datetime import datetime as dt

List = [
    ('John', '12345', '1972-02-08'),
    ('Sara', '12345', '1977-07-01'),
    ('Mario', '12345', '1971-06-13'),
    ('Lucas', '12345', '1967-04-27'),
    ('Kiara', '12345', '1973-02-15')
]

print(sorted(List, key=lambda x: dt.strptime(x[2], '%Y-%m-%d')))
print(sorted(List, key=lambda x: x[2]))

Prints

[('Lucas', '12345', '1967-04-27'), ('Mario', '12345', '1971-06-13'), ('John', '12345', '1972-02-08'), ('Kiara', '12345', '1973-02-15'), ('Sara', '12345', '1977-07-01')]
[('Lucas', '12345', '1967-04-27'), ('Mario', '12345', '1971-06-13'), ('John', '12345', '1972-02-08'), ('Kiara', '12345', '1973-02-15'), ('Sara', '12345', '1977-07-01')]

Comments

  • Since the dates are in ISO format, you can just sort them as strings, you don’t need to parse them. – Barmar
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading