基于时间排序的python字典

问题描述 投票:0回答:3

我有如下字典。

d = {
    '0:0:7': '19734',
    '0:0:0': '4278',
    '0:0:21': '19959',
    '0:0:14': '9445',
    '0:0:28': '14205',
    '0:0:35': '3254'
}

现在,我想按具有时间优先级的键对其进行排序。

python python-3.x sorting dictionary ordereddictionary
3个回答
1
投票

字典未排序,如果要按排序顺序打印出来或遍历字典,应先将其转换为列表:

例如:

sorted_dict = sorted(d.items(), key=parseTime)
#or
for t in sorted(d, key=parseTime):
    pass

def parseTime(s):
    return tuple(int(x) for x in s.split(':'))

注意,这意味着您不能将d ['0:0:7']语法用于sorted_dict。

将'key'参数传递给sorted告诉python如何比较列表中的项目,标准字符串比较无法按时间进行排序。


1
投票

python中的字典无法保证顺序。有collections.OrderedDict,保留插入顺序,但是如果您想按顺序浏览标准字典的键,则可以执行以下操作:

for k in sorted(d):

对于您而言,问题是您的时间字符串无法正确排序。您需要添加使其成为必需的其他零,例如"00:00:07",或将它们解释为实际的time对象,它们将正确排序。此功能可能有用:

def padded(s, c=":"):
    return c.join("{0:02d}".format(int(i)) for i in s.split(c))

如果您确实想在输出中保留当前格式,则可以将其用作keysorted

for k in sorted(d, key=padded):

0
投票
© www.soinside.com 2019 - 2024. All rights reserved.