您無法對標準字典進行排序,但可以排序並顯示項目。
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'}}
字典沒有訂單,所以無法排序。你想要輸出爲'(鍵,值)'元組列表嗎? –
不知道這件事。好的,將其更改爲列表。謝謝! – Apache