📜  Python|按日期对给定的字典列表进行排序

📅  最后修改于: 2022-05-13 01:54:23.181000             🧑  作者: Mango

Python|按日期对给定的字典列表进行排序

给定一个字典列表,任务是按日期对字典进行排序。让我们看一些解决任务的方法。

方法#1:使用朴素的方法

# Python code to demonstrate
# sort a list of dictionary
# where value date is in string
  
# Initialising list of dictionary
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'}]
                  
# printing initial list
print ("initial list : ", str(ini_list))
  
# code to sort list on date
ini_list.sort(key = lambda x:x['d.o.b'])
  
# printing final list
print ("result", str(ini_list))
输出:

方法 #2:使用datetime.strptimelambda

# Python code to demonstrate
# sort a list of dictionary
# where value date is in a string
  
from datetime import datetime
  
# Initialising list of dictionary
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'}]
                  
# printing initial list
print ("initial list : ", str(ini_list))
  
# code to sort list on date
ini_list.sort(key = lambda x: datetime.strptime(x['d.o.b'], '%Y-%m-%d'))
  
# printing final list
print ("result", str(ini_list))
输出:


方法 #3:使用operator.itemgetter

# Python code to demonstrate
# sort a list of dictionary
# where value date is in string
  
import operator
  
# Initialising list of dictionary
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'}]
                  
# printing initial list
print ("initial list : ", str(ini_list))
  
# code to sort list on date
ini_list.sort(key = operator.itemgetter('d.o.b'))
  
# printing final list
print ("result", str(ini_list))
输出: