Reputation: 29
I created a dict of lists as such.
{'chans': [['24', 'X', 'RCP', '8400.0', 'mex', '325.0K', '8', '50 1', '17', 266, **datetime.time(22, 0)**, '17', 266, datetime.time(23, 0), '00', '23', '00', 20.604799168660975, '041'],
['24', 'X', 'RCP', '8400.0', 'ody', '325.0K', '4', '40 1', '17', 266, **datetime.time(17, 0)**, '17', 266, datetime.time(18, 0), '00', '18', '00', 16.31949387241184, '053'],
['24', 'X', 'RCP', '8400.0', 'mro', '325.0K', '8', '50 1', '17', 266, **datetime.time(18, 0)**, '17', 266, datetime.time(19, 0), '00', '19', '00', 27.872042154574956, '074']]}
I need to sort this in ascending order by using the date time object (element 10 in each list). I'm stuck at determining the proper key/value. In essence, I'm not sure what to do.
Upvotes: 0
Views: 775
Reputation: 3822
You can use itemgetter, and just select the index of the item in the list not dict, we can't order a dictionnary,
from operator import itemgetter
import datetime
f = {'chans': [['24', 'X', 'RCP', '8400.0', 'mex', '325.0K', '8', '50 1', '17', 266, """datetime.time(22, 0)""", '17', 266, datetime.time(23, 0), '00', '23', '00', 20.604799168660975, '041'],
['24', 'X', 'RCP', '8400.0', 'ody', '325.0K', '4', '40 1', '17', 266, """datetime.time(17, 0)""", '17', 266, datetime.time(18, 0), '00', '18', '00', 16.31949387241184, '053'],
['24', 'X', 'RCP', '8400.0', 'mro', '325.0K', '8', '50 1', '17', 266, """datetime.time(18, 0)""", '17', 266, datetime.time(19, 0), '00', '19', '00', 27.872042154574956, '074']]}
sorted(f['chans'], key=itemgetter(10))
Upvotes: 1
Reputation: 5425
sort
functionThere is a sort
function (in-place) and a sorted
function (returns list sorted). Each of these takes an optional argument called key
, which is called on each element for comparison. In your case, you want to call sort(dictionary["chans"])
, which will sort the lists. Since you want to sort by the 11th element in each list, you would do this:
sort(dictionary["chans"], key = lambda sublist: sublist[10])
The key takes a sublist and returns its 11th element, so sort
is sorting the sublists by their 11th elements (the datetime).
You can make key
whatever you want to suit your needs.
Upvotes: 0