简体   繁体   English

按值对日期字典列表进行排序

[英]Sort a list of dictionaries of dates by value

I'm trying to sort the values with current year.我正在尝试对当前年份的值进行排序。

Current year values should show first.当前年份值应首先显示。

mdlist = [{0:'31 Jan 2022', 1:'', 2:'10 Feb 2022'},
          {0:'10 Feb 2021', 1:'20, Feb 2021', 2:''}, 
          {0:'10 Feb 2022', 1:'10 Feb 2022', 2:'10 Feb 2022'}]
mdlist = sorted(mdlist, key=lambda d:d[0])

but it is not working as expected但它没有按预期工作

expected output:预计 output:

mdlist = [{0:'31 Jan 2022', 1:'', 2:'10 Feb 2022'},
          {0:'10 Feb 2022', 1:'10 Feb 2022', 2:'10 Feb 2022'},
          {0:'10 Feb 2021', 1:'20 Feb 2021', 2:''}]

Maybe you could leverage the fact that these are datetimes by using the datetime module and sort it by the years in descending order and the month-days in ascending order:也许您可以通过使用datetime模块来利用这些是日期时间这一事实,并按年份降序排序,月-日按升序排序:

from datetime import datetime
def sorting_key(dct):
    ymd = datetime.strptime(dct[0], "%d %b %Y")
    return -ymd.year, ymd.month, ymd.day

mdlist.sort(key=sorting_key)

Output: Output:

[{0: '31 Jan 2022', 1: '', 2: '10 Feb 2022'},
 {0: '10 Feb 2022', 1: '10 Feb 2022', 2: '10 Feb 2022'},
 {0: '10 Feb 2021', 1: '20 Feb 2021', 2: ''}]

Use a key function that returns 0 if the year is 2022 , 1 otherwise.使用key function 如果年份是2022则返回0 ,否则返回1 This will sort all the 2022 dates first.这将首先对所有 2022 年的日期进行排序。

firstyear = '2022'
mdlist = sorted(mdlist, key=lambda d: 0 if d:d[0].split()[-1] == firstyear else 1)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM