首页 > 解决方案 > 如何按值对字典进行排序

问题描述

我正在尝试按值对字典进行排序,该值是格式中的时间戳H:MM:SS(例如“0:41:42”),但下面的代码无法按预期工作:

album_len = {
    'The Piper At The Gates Of Dawn': '0:41:50',
    'A Saucerful of Secrets': '0:39:23',
    'More': '0:44:53', 'Division Bell': '1:05:52',
    'The Wall': '1:17:46',
    'Dark side of the moon': '0:45:18',
    'Wish you were here': '0:44:17',
    'Animals': '0:41:42'
}
album_len = OrderedDict(sorted(album_len.items()))

这是我得到的输出:

OrderedDict([
    ('A Saucerful of Secrets', '0:39:23'),
    ('Animals', '0:41:42'),
    ('Dark side of the moon', '0:45:18'),
    ('Division Bell', '1:05:52'),
    ('More', '0:44:53'),
    ('The Piper At The Gates Of Dawn', '0:41:50'),
    ('The Wall', '1:17:46'),
    ('Wish you were here', '0:44:17')])

它不应该是那样的。我希望看到的第一个元素是 ('The Wall', '1:17:46'),最长的一个。

如何按照我的预期对元素进行排序?

标签: python

解决方案


尝试将每个值转换为日期时间并将其用作键:

from collections import OrderedDict
from datetime import datetime


def convert_to_datetime(val):
    return datetime.strptime(val, "%H:%M:%S")


album_len = {'The Piper At The Gates Of Dawn': '0:41:50',
             'A Saucerful of Secrets': '0:39:23', 'More': '0:44:53',
             'Division Bell': '1:05:52', 'The Wall': '1:17:46',
             'Dark side of the moon': '0:45:18',
             'Wish you were here': '0:44:17', 'Animals': '0:41:42'}
album_len = OrderedDict(
    sorted(album_len.items(), key=lambda i: convert_to_datetime(i[1]))
)
print(album_len)

输出:

OrderedDict([('A Saucerful of Secrets', '0:39:23'), ('Animals', '0:41:42'),
             ('The Piper At The Gates Of Dawn', '0:41:50'),
             ('Wish you were here', '0:44:17'), ('More', '0:44:53'),
             ('Dark side of the moon', '0:45:18'), ('Division Bell', '1:05:52'),
             ('The Wall', '1:17:46')])

或按降序排列,将 reverse 设置为 True:

album_len = OrderedDict(
    sorted(
        album_len.items(),
        key=lambda i: convert_to_datetime(i[1]),
        reverse=True
    )
)

输出:

OrderedDict([('The Wall', '1:17:46'), ('Division Bell', '1:05:52'),
             ('Dark side of the moon', '0:45:18'), ('More', '0:44:53'),
             ('Wish you were here', '0:44:17'),
             ('The Piper At The Gates Of Dawn', '0:41:50'),
             ('Animals', '0:41:42'), ('A Saucerful of Secrets', '0:39:23')])

编辑:如果只需要维护插入顺序并且不使用OrderedDict特定功能move_to_end,那么常规 pythondict也适用于 Python3.7+。

上升:

album_len = dict(
    sorted(album_len.items(), key=lambda i: convert_to_datetime(i[1]))
)

降序:

album_len = dict(
    sorted(album_len.items(), key=lambda i: convert_to_datetime(i[1]),
           reverse=True)
)

推荐阅读