Islarf Islarf - 3 months ago 8
Python Question

Sort list of dicts by multiple values

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.

Answer

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.

Comments