我有这样的字典:
{
'28.10.11/D/text1/' : {key:value1},
'27.01.11/D/text2/' : {key:value2},
'07.11.12/D/text3/' : {key:value3}
}
部分密钥基于日期,即以“%d。%m。%Y”格式设置的日期。需要按日期对所有字典键进行排序。值必须以相同的格式保存。例如:
{
'27.01.11/D/text2/' : {key:value2},
'28.10.11/D/text1/' : {key:value1},
'07.11.12/D/text3/' : {key:value3}
}
答案 0 :(得分:4)
您无法对标准词典进行排序,但您可以对项目进行排序和显示。
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'}}
答案 1 :(得分:2)
将sorted
函数与key
参数一起使用。编写key
函数,将字符串转换为Datetime
,并根据Datetime
进行排序。
def remap_key(key):
from datetime import datetime
a = key.split('/')[0]
return datetime.strptime(a, "%d.%m.%y")
>>> d = {
... '27.01.11/D/text2/' : "a",
... '28.10.11/D/text1/' : "b",
... '07.11.12/D/text3/' : "c"
... }
>>>
>>> def remap_key(key):
... from datetime import datetime
... a = key.split('/')[0]
... return datetime.strptime(a, "%d.%m.%y")
...
>>> sorted(d, key=remap_key)
['27.01.11/D/text2/', '28.10.11/D/text1/', '07.11.12/D/text3/']
或按iteritems
排序:
>>> def remap_key(key_pair):
... from datetime import datetime
... key = key_pair[0]
... a = key.split('/')[0]
... return datetime.strptime(a, "%d.%m.%y")
...
>>> sorted(d.iteritems(), key=remap_key)
[('27.01.11/D/text2/', 'a'), ('28.10.11/D/text1/', 'b'), ('07.11.12/D/text3/', 'c')]
答案 2 :(得分:1)
作为另一种选择,您可以将OrderedDict与日期时间结合使用(如hughdbrown所述):
>>> from collections import OrderedDict
>>> from datetime import datetime
>>> d = {
'28.10.11/D/text1/' : {'key1':'value1'},
'27.01.11/D/text2/' : {'key2':'value2'},
'07.11.12/D/text3/' : {'key3':'value3'}
}
>>> OrderedDict(sorted(d.items(), key=lambda t: datetime.strptime(t[0][:8], "%d.%m.%y")))
结果:
OrderedDict([('27.01.11/D/text2/', {'key2': 'value2'}), ('28.10.11/D/text1/', {'key1': 'value1'}), ('07.11.12/D/text3/', {'key3': 'value3'})])
您将获得您正在寻找的订单,并且日期的每个部分将以常规方式与其他日期的相应部分进行比较。