Python Forum

Full Version: sorting a list of tuples based on date
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi

I am unsure whether the tuple is sorted or not.
There appears to be no difference to the list of tuples after being sorted.
#!/usr/bin/python3
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)
The output is as:
Before sorting
 [('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')]

After sorting
 [('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')]
Any ideas how I can view the sorted phone list ?
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)
To sort a list in place, use the sort method of the list (phones.sort(key = get_key)).