0

For the following data, I am looking to sort the data first by the "date" property, and then by the "name" property.

Input:
results = {
   "a":{
      "date":"20140206",
      "bytes":"154",
      "name":"cos"
   },
   "b":{
      "date":"20140207",
      "bytes":"300",
      "name":"cos"
   },
   "c":{
      "date":"20140206",
      "bytes":"279",
      "name":"phil"
   },
   "d":{
      "date":"20140207",
      "bytes":"241",
      "name":"phil"
   }
}

I am trying the following code which works but I am not sure how it is sorting first by date and then by name.

results = collections.OrderedDict(sorted(results.items()))
Output:
results = {
   "a":{
      "date":"20140206",
      "bytes":"154",
      "name":"cos"
   },
   "c":{
      "date":"20140206",
      "bytes":"279",
      "name":"phil"
   },
   "b":{
      "date":"20140207",
      "bytes":"300",
      "name":"cos"
   },
   "d":{
      "date":"20140207",
      "bytes":"241",
      "name":"phil"
   }
}

Is there any other way to do it where I can explicitly specify to first sort by date property and then by name property?

2
  • you can pass key argument to sorted.
    – buran
    Commented Oct 6, 2022 at 6:11
  • It sorts by keys from a to d. It doesn't sort how you wan't. What you want is to use key kwarg that returns tuple of items to compare with Commented Oct 6, 2022 at 6:11

1 Answer 1

0

You have to use key= for custom sorting.

If you want to sort first by date then by name you need to use tuple of them as a sorting key

results = collections.OrderedDict(sorted(results.items(), key=lambda s: (s[1]['date'], s[1]['name'])))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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