You can give a key
to tell list.sort
or sorted
how to sort.
A key to sort by the first value is lambda x: x[0]
; a key to sort by the second value is lambda x: x[1]
.
d = {'user_0': [['item_805696', '2021-02-11 13:03:42'],
['item_849824', '2021-02-11 13:05:04'],
['item_386903', '2021-02-11 13:03:52'],
['item_3832', '2021-02-11 13:04:07']],
'user_1': [['item_58840', '2021-02-11 13:16:11'],
['item_947129', '2021-02-11 13:15:27'],
['item_97057', '2021-02-11 13:03:42'],
['item_640213', '2021-02-11 13:17:40'],
['item_644971', '2021-02-11 13:09:32']]}
for v in d.values():
v.sort(key=lambda x: x[1])
print(d)
# {'user_0': [['item_805696', '2021-02-11 13:03:42'],
# ['item_386903', '2021-02-11 13:03:52'],
# ['item_3832', '2021-02-11 13:04:07'],
# ['item_849824', '2021-02-11 13:05:04']],
# 'user_1': [['item_97057', '2021-02-11 13:03:42'],
# ['item_644971', '2021-02-11 13:09:32'],
# ['item_947129', '2021-02-11 13:15:27'],
# ['item_58840', '2021-02-11 13:16:11'],
# ['item_640213', '2021-02-11 13:17:40']]}
Note that this only works because the timestamps are presented in the very practical format 'yyyy-mm-dd HH:MM:SS'
, and strings are sorted lexicographically, i.e., from left to right. If the timestamps had been in a less friendly format, such as 'dd-mm-yyyy HH:MM:SS'
, then you'd need to use the key to parse the timestamps.