Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort list of dicts by multiple values [duplicate]

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.

like image 856
Islarf Avatar asked Aug 05 '16 12:08

Islarf


1 Answers

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.

like image 107
Eswcvlad Avatar answered Nov 08 '22 22:11

Eswcvlad