📜  按日期排序 python 字典 - Python 代码示例

📅  最后修改于: 2022-03-11 14:46:03.668000             🧑  作者: Mango

代码示例1
from datetime import datetime
from collections import OrderedDict # For python 2.7 and above

data = { "01-01-2015" : "some data",
         "05-05-2015" : "some data",
         "03-04-2015" : "some data" }

# For python 2.7 and above:
ordered_data = OrderedDict(
    sorted(data.items(), key = lambda x:datetime.strptime(x[0], '%d-%m-%Y')) )

# For python 2.6 and below where OrderedDict is not present:
# ordered_data = sorted(data.items(), key = lambda x:datetime.strptime(x[0], '%d-%m-%Y'))

print(ordered_data)

#Output :
[('01-01-2015', 'some data'), 
 ('03-04-2015', 'some data'), 
 ('05-05-2015', 'some data')]