TheNumber23
TheNumber23

Reputation: 383

sorting a list by key then value in python

I have a list whose keys is the date and the value is the hour of that day a sample looks like this

dtlist = [{'26/12/2010','01'},{'27/3/2008','00'},{'7/7/2007','10'},{'7/7/2007','23'}]

The output that I should get is

dtlist= [{'7/7/2007','10'},{'7/7/2007','23'},{'27/3/2008','00'},{'26/12/2010','01'}]

I want the date to be sorted by year, month, day and when the date is the same sort by hour in increasing order. Many thanks.

Upvotes: 2

Views: 66

Answers (1)

Drathier
Drathier

Reputation: 14539

You have a list of unordered set litterals. I'm assuming you actually want to use something else, like a list of lists, or a list of tuples.

Here's how you can do it with a list of lists, or a list of tuples:

a = [['26/12/2010','01'],['27/3/2008','00'],['7/7/2007','10'],['7/7/2007','23']]

def k(a):
    d = list(map(int, a[0].split("/")))
    return d[::-1] + [int(a[1])]

print(sorted(a, key=k))

outputs: [['7/7/2007', '10'], ['7/7/2007', '23'], ['27/3/2008', '00'], ['26/12/2010', '01']]

The key function returns the key for an item in the list, which is then used by the sorting function to sort the list.

In this example your input data corresponds to these keys:

items: [['7/7/2007', '10'], ['7/7/2007', '23'], ['27/3/2008', '00'], ['26/12/2010', '01']]
keys:  [[2007, 7, 7, 10],   [2007, 7, 7, 23],   [2008, 3, 27, 0],    [2010, 12, 26, 1]]

We thus sort by year, followed by month, followed by day, and lastly hour.

Upvotes: 1

Related Questions