Python Forum
sorting a list of tuples based on date
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
sorting a list of tuples based on date
#2
Sure, sorted() as your using it generates a new list without altering the old one so try:

import operator
from datetime import datetime

phones = [('Samsung S7', '11 March 2016'), ('Samsung S8','29 March 2017'), ('Samsung S9', '16 March 2018'),
        ('Google Pixel', '20 October 2016'),('Google Pixel 2', '21 October 2017'),
        ('Apple iPhone 7', '7 September 2016'),('Apple iPhone 8','1 September 2017'),('Apple iPhone 9', '12 September 2018')]

def get_key(phone_record):
  return datetime.strptime(phone_record[1], '%d %B %Y')

print("Before sorting\n", phones)
sorted(phones, key=get_key)
print("\nAfter sorting\n", phones)

x = sorted(phones, key= get_key)

print(x)
Reply


Messages In This Thread
RE: sorting a list of tuples based on date - by Vysero - Aug-09-2018, 09:37 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Compare current date on calendar with date format file name Fioravanti 1 2,297 Mar-26-2024, 08:23 AM
Last Post: Pedroski55
  unable to remove all elements from list based on a condition sg_python 3 1,813 Jan-27-2024, 04:03 PM
Last Post: deanhystad
  Create dual folder on different path/drive based on the date agmoraojr 2 1,448 Jan-21-2024, 10:02 AM
Last Post: snippsat
  Python date format changes to date & time 1418 4 2,962 Jan-20-2024, 04:45 AM
Last Post: 1418
  Adding values with reduce() function from the list of tuples kinimod 10 5,811 Jan-24-2023, 08:22 AM
Last Post: perfringo
  List Sorting Problem ZZTurn 5 2,844 Sep-22-2022, 11:23 PM
Last Post: ZZTurn
  select Eof extension files based on text list of filenames with if condition RolanRoll 1 2,309 Apr-04-2022, 09:29 PM
Last Post: Larz60+
  Sorting List finndude 9 4,290 Jan-27-2022, 09:37 PM
Last Post: Pedroski55
  Date format and past date check function Turtle 5 10,870 Oct-22-2021, 09:45 PM
Last Post: deanhystad
  sorting a list of lists by an element leapcfm 3 2,974 Sep-10-2021, 03:33 PM
Last Post: leapcfm

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020