7

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.

2
  • Thank you @Mephy I couldn't find that one, that's perfect! I'll leave this question here, as my one does reference to dicts/lists, and the other is referring to lists/tuples.
    – Islarf
    Commented Aug 5, 2016 at 12:52
  • Why are these questions always f'ing easy INTs!
    – Micah B.
    Commented Jul 23, 2021 at 19:12

1 Answer 1

16

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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.