您无法对标准字典进行排序,但可以对项目进行排序和显示。
from datetime import datetime
D = {'28.10.11/D/text1/' : {'key':'value1'},
'27.01.11/D/text2/' : {'key':'value2'},
'07.11.12/D/text3/' : {'key':'value3'}}
for k in sorted(D,key=lambda k: datetime.strptime(k[:8],"%d.%m.%y")):
print(k,D[k])
输出:
27.01.11/D/text2/ {'key': 'value2'}
28.10.11/D/text1/ {'key': 'value1'}
07.11.12/D/text3/ {'key': 'value3'}
如果要使用列表:
from datetime import datetime
from pprint import pprint
L = [('28.10.11/D/text1/' , {'key':'value1'}),
('27.01.11/D/text2/' , {'key':'value2'}),
('07.11.12/D/text3/' , {'key':'value3'})]
L.sort(key=lambda k: datetime.strptime(k[0][:8],"%d.%m.%y"))
pprint(L)
输出:
[('27.01.11/D/text2/', {'key': 'value2'}),
('28.10.11/D/text1/', {'key': 'value1'}),
('07.11.12/D/text3/', {'key': 'value3'})]
最后,如果您仍然想要字典行为,OrderedDict 会记住插入的顺序键,因此:
from collections import OrderedDict
from datetime import datetime
from pprint import pprint
D = {'28.10.11/D/text1/' : {'key':'value1'},
'27.01.11/D/text2/' : {'key':'value2'},
'07.11.12/D/text3/' : {'key':'value3'}}
OD = OrderedDict(sorted(D.items(),
key=lambda k: datetime.strptime(k[0][:8],"%d.%m.%y"))
pprint(OD)
输出:
{'27.01.11/D/text2/': {'key': 'value2'},
'28.10.11/D/text1/': {'key': 'value1'},
'07.11.12/D/text3/': {'key': 'value3'}}