【发布时间】:2021-05-08 02:57:12
【问题描述】:
第二次尝试这个问题。我已经更改了 2 个建议的答案,但它们并没有解决我的问题。 我的字典是这样的:
old_list = {
"x": {
"bd_date": "04/01/1977",
"name": "Deli Mirko",
"next": "04/02/2021",
"renew": 1,
"type": "birthday",
"until": 335
},
"y": {
"bd_date": "25/11/1983",
"name": "Deli Marina",
"next": "25/11/2021",
"renew": 1,
"type": "birthday",
"until": 295
},
.....
}
我希望使用“直到”值 ASC 对其进行排序。
有没有办法做到这一点。
我尝试了建议的解决方案, Sort nested dictionary by values Sort nested dictionary by value, and remainder by another value, in Python
但我没有得到结果,或者它改变了我的字典格式。我需要保持格式,因为其余的代码。 我试过了
new_list = sorted(old_list.items(), key=lambda i: i[1]['until'])
但它会将格式更改为从 dict 列表 - [("x",{...}), ("y",{..})...]
那么,如何更改上述代码以保持格式 {"x": {...}, "y": {...}}
这很重要,因为稍后在代码中我使用循环输出数据
events_keys = old_list.keys()
for events_key in events_keys:
event = old_list[events_key]
# Get values for each event
tmp_bd = event['bd_date']
tmp_name = event['name']
....
所以我想我需要先对 dict 进行排序,所以打印的值是按升序排列的?!
【问题讨论】:
标签: python python-3.x dictionary