Python | Sort given list of dictionaries by date
Last Updated :
14 Mar, 2023
Given a list of dictionary, the task is to sort the dictionary by date. Let’s see a few methods to solve the task. Method #1: Using naive approach
Python3
ini_list = [{ 'name' : 'akash' , 'd.o.b' : '1997-03-02' },
{ 'name' : 'manjeet' , 'd.o.b' : '1997-01-04' },
{ 'name' : 'nikhil' , 'd.o.b' : '1997-09-13' }]
print ("initial list : ", str (ini_list))
ini_list.sort(key = lambda x:x[ 'd.o.b' ])
print ("result", str (ini_list))
|
Output:
initial list : [{‘name’: ‘akash’, ‘d.o.b’: ‘1997-03-02’}, {‘name’: ‘manjeet’, ‘d.o.b’: ‘1997-01-04’}, {‘name’: ‘nikhil’, ‘d.o.b’: ‘1997-09-13’}] result [{‘name’: ‘manjeet’, ‘d.o.b’: ‘1997-01-04’}, {‘name’: ‘akash’, ‘d.o.b’: ‘1997-03-02’}, {‘name’: ‘nikhil’, ‘d.o.b’: ‘1997-09-13’}]
The time complexity of the above Python code is O(n log n), where ‘n’ is the number of dictionaries in the list.
The auxiliary space complexity of the code is O(1), as it only uses a constant amount of additional space, regardless of the size of the input.
Method #2: Using datetime.strptime and lambda
Python3
from datetime import datetime
ini_list = [{ 'name' : 'akshat' , 'd.o.b' : '1997-09-01' },
{ 'name' : 'vashu' , 'd.o.b' : '1997-08-19' },
{ 'name' : 'manjeet' , 'd.o.b' : '1997-01-04' },
{ 'name' : 'nikhil' , 'd.o.b' : '1997-09-13' }]
print ("initial list : ", str (ini_list))
ini_list.sort(key = lambda x: datetime.strptime(x[ 'd.o.b' ], '%Y-%m-%d' ))
print ("result", str (ini_list))
|
Output:
initial list : [{‘d.o.b’: ‘1997-09-01’, ‘name’: ‘akshat’}, {‘d.o.b’: ‘1997-08-19’, ‘name’: ‘vashu’}, {‘d.o.b’: ‘1997-01-04’, ‘name’: ‘manjeet’}, {‘d.o.b’: ‘1997-09-13’, ‘name’: ‘nikhil’}] result [{‘d.o.b’: ‘1997-01-04’, ‘name’: ‘manjeet’}, {‘d.o.b’: ‘1997-08-19’, ‘name’: ‘vashu’}, {‘d.o.b’: ‘1997-09-01’, ‘name’: ‘akshat’}, {‘d.o.b’: ‘1997-09-13’, ‘name’: ‘nikhil’}]
Method #3: Using operator.itemgetter
Python3
import operator
ini_list = [{ 'name' : 'akash' , 'd.o.b' : '1997-03-02' },
{ 'name' : 'manjeet' , 'd.o.b' : '1997-01-04' },
{ 'name' : 'nikhil' , 'd.o.b' : '1997-09-13' }]
print ("initial list : ", str (ini_list))
ini_list.sort(key = operator.itemgetter( 'd.o.b' ))
print ("result", str (ini_list))
|
Output:
initial list : [{‘d.o.b’: ‘1997-03-02’, ‘name’: ‘akash’}, {‘d.o.b’: ‘1997-01-04’, ‘name’: ‘manjeet’}, {‘d.o.b’: ‘1997-09-13’, ‘name’: ‘nikhil’}] result [{‘d.o.b’: ‘1997-01-04’, ‘name’: ‘manjeet’}, {‘d.o.b’: ‘1997-03-02’, ‘name’: ‘akash’}, {‘d.o.b’: ‘1997-09-13’, ‘name’: ‘nikhil’}]
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...