I have the following dict
tempdata = {'logs': [
{'starttime':'901',
'time':'5'
},
{'starttime':'902',
'time':'3'
},
{'starttime':'900',
'time':'2'
},
{'starttime':'901',
'time':'2'
},
{'starttime':'905',
'time':'1'
},
{'starttime':'904',
'time':'1'
}
]
}
I want to primarily sort by starttime
. Which I do perfectly with:
tempdata['logs'] = sorted(tempdata['logs'],key=lambda k: k['starttime'])
But now, I want to sort them by time as well.
Expected output:
tempdata = {'logs': [
{'starttime':'900',
'time':'2'
},
{'starttime':'901',
'time':'2'
},
{'starttime':'901',
'time':'5'
},
{'starttime':'902',
'time':'3'
},
{'starttime':'904',
'time':'1'
},
{'starttime':'905',
'time':'1'
}
]
}
How can I accomplish this task? I've looked up the sorted(), and can't find what I'm looking for.
Sort them using a tuple as a key like this:
tempdata['logs'] = sorted(tempdata['logs'],
key=lambda k: (k['starttime'], k['time']))
Tuples are compared by each element in order.
And as a side note, this way the values are compared as strings, not as numbers. Don't know if that's relevant for you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With