gpt4 book ai didi

Python:按部分键对多级字典进行排序

转载 作者:行者123 更新时间:2023-11-28 20:48:58 26 4
gpt4 key购买 nike

我有这样的字典:

{
'28.10.11/D/text1/' : {key:value1},
'27.01.11/D/text2/' : {key:value2},
'07.11.12/D/text3/' : {key:value3}
}

部分 key 基于日期,以“%d.%m.%Y”格式设置。需要按日期对所有字典键进行排序。值必须以相同的格式保存。示例:

{
'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

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'}}

关于Python:按部分键对多级字典进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15720793/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com