How to sort a dictionary based on different key fields?
I have a dictionary that contains id,Direction,year,month,day,hour
and I want to sort based on month,day,hour
. Below is my dictionary and its meanings:
table = {('2339', 'W', '2016', '6', '2', '11'): [0],
('2339', 'W', '2016', '1', '16', '8'): [0],
('2339', 'W', '2016', '5', '8', '22'): [2],
('2339', 'W', '2016', '1', '17', '3'): [0]}
and the code I used to sort:
result_dict = sorted(table.items(), key=operator.itemgetter(0))
But that won't sort the way I want. How can I sort it by month, day and hour. The result I want looks like this:
ID Direction year month day hour 2339 W 2016 1 1 0 2339 W 2016 1 1 1 2339 W 2016 1 1 2 2339 W 2016 1 1 3 ... .. .. .. .. ..
source to share
Assuming the sort implies lexicography among values โโand ascending to all coordinates, you can use the default sort, which is lexicographic.
For example:
items = [(0, 1, 2), (0, 0, 2), (1, 0, 0)]
s1 = sorted(items) # [(0, 0, 2), (0, 1, 2), (1, 0, 0)]
s2 = sorted(items, key=lambda t: (t[1], t[2])) # [(1, 0, 0), (0, 0, 2), (0, 1, 2)]
And in the case of the original dictionary table
:
result_dict = sorted(table.items(), key=lambda pair: (int(pair[0][3]),
int(pair[0][4]),
int(pair[0][5])))
# [(('2339', 'W', '2016', '1', '16', '8'), [0]),
# (('2339', 'W', '2016', '1', '17', '3'), [0]),
# (('2339', 'W', '2016', '5', '8', '22'), [2]),
# (('2339', 'W', '2016', '6', '2', '11'), [0])]
source to share
The last four entries in your tuple are already configured with decreasing significance. So just slice them up and use the default tuple comparison. Note that you will need to match the strings to integers and compare them correctly (otherwise '10' < '2'
).
sorted_keys = sorted(table, key=lambda k: map(int, k[2:]))
print sorted_keys
# [('2339', 'W', '2016', '1', '16', '8'),
# ('2339', 'W', '2016', '1', '17', '3'),
# ('2339', 'W', '2016', '5', '8', '22'),
# ('2339', 'W', '2016', '6', '2', '11')]
You can then iterate over that set of keys to do what you would like to do.
source to share