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.

Islarf
  • 159
  • 3
  • 11
  • 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 Aug 05 '16 at 12:52
  • Why are these questions always f'ing easy INTs! – Micah B. Jul 23 '21 at 19:12

1 Answers1

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.

Eswcvlad
  • 796
  • 7
  • 9