Search code examples
pythonpython-3.xsortingdictionaryordereddictionary

python dictionary sorted based on time


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.


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.