【问题标题】:Sorting dictionary by key按键排序字典
【发布时间】:2021-11-27 04:55:27
【问题描述】:

我有一本字典,其中有年月组合作为它的键和值。我使用 OrderedDict 对字典进行排序并获得如下结果。在我的预期结果中,在“2021-1”之后,应该是“2021-2”。但是“2021-10”介于两者之间。

{
    "2020-11": 25,
    "2020-12": 861,
    "2021-1": 935,
    "2021-10": 1,
    "2021-2": 4878,
    "2021-3": 6058,
    "2021-4": 3380,
    "2021-5": 4017,
    "2021-6": 1163,
    "2021-7": 620,
    "2021-8": 300,
    "2021-9": 7
}

我的预期结果应该如下所示。我希望字典按到最后日期的最短日期排序

{
        "2020-11": 25,
        "2020-12": 861,
        "2021-1": 935,
        "2021-2": 4878,
        "2021-3": 6058,
        "2021-4": 3380,
        "2021-5": 4017,
        "2021-6": 1163,
        "2021-7": 620,
        "2021-8": 300,
        "2021-9": 7,
        "2021-10": 1
    }

如果您能提供帮助,不胜感激。

【问题讨论】:

  • 那是因为词法字符串排序。将您的日期格式修复为始终具有两位数的月份(例如2021-01),问题就消失了。
  • 字符串按字典顺序排序。 提示:使用datetime模块解析字符串,然后对datetime对象进行排序。

标签: python-3.x ordereddict


【解决方案1】:

如果你想自定义排序的方式,使用sorted和参数key

from typing import OrderedDict
from decimal import Decimal


data = {
    "2020-11": 25,
    "2020-12": 861,
    "2021-1": 935,
    "2021-10": 1,
    "2021-2": 4878,
    "2021-3": 6058,
    "2021-4": 3380,
    "2021-5": 4017,
    "2021-6": 1163,
    "2021-7": 620,
    "2021-8": 300,
    "2021-9": 7
}

def year_plus_month(item):
    key = item[0].replace("-", ".")
    return Decimal(key)

data_ordered = OrderedDict(sorted(data.items(), key=year_plus_month))
print(data_ordered)

我使用Decimal 而不是float 来避免任何不稳定的浮点精度。

【讨论】:

    猜你喜欢
    • 2011-06-17
    • 2015-10-10
    • 2012-07-30
    • 1970-01-01
    • 2017-08-20
    • 2016-11-22
    • 2017-05-30
    • 2020-06-09
    相关资源
    最近更新 更多