【问题标题】:How to sort dictionary with keys, using certain field in dict - Python 3如何使用字典中的某些字段对字典进行排序 - Python 3
【发布时间】: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


    【解决方案1】:

    只需对排序结果使用字典理解即可。这是因为从 Python 3.6 开始,标准 dict 类型默认保持插入顺序。

    new_list = {k:v for k, v in sorted(old_list.items(), key=lambda i: i[1]['until'])}
    

    新列表:

    {'y': {'bd_date': '25/11/1983',
      'name': 'Deli Marina',
      'next': '25/11/2021',
      'renew': 1,
      'type': 'birthday',
      'until': 295},
     'x': {'bd_date': '04/01/1977',
      'name': 'Deli Mirko',
      'next': '04/02/2021',
      'renew': 1,
      'type': 'birthday',
      'until': 335}}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-11-10
      • 2023-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-12
      • 2014-01-23
      • 2010-10-28
      相关资源
      最近更新 更多