Question

I have a dictionary such as below.

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'
}

Now I want to sort it by keys with time priority.

Was it helpful?

Solution

Dictionaries are not sorted, if you want to print it out or iterate through it in sorted order, you should convert it to a list first:

e.g.:

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(':'))

Note that this will mean you can not use the d['0:0:7'] syntax for sorted_dict though.

Passing a 'key' argument to sorted tells python how to compare the items in your list, standard string comparison will not work to sort by time.

OTHER TIPS

Dictionaries in python have no guarantees on order. There is collections.OrderedDict, which retains insertion order, but if you want to work through the keys of a standard dictionary in order you can just do:

for k in sorted(d):

In your case, the problem is that your time strings won't sort correctly. You need to include the additional zeroes needed to make them do so, e.g. "00:00:07", or interpret them as actual time objects, which will sort correctly. This function may be useful:

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

You can use this as a key for sorted if you really want to retain the current format in your output:

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

Have a look at the collections.OrderedDict module

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top