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?
key
argument to sorted.a
tod
. It doesn't sort how you wan't. What you want is to usekey
kwarg that returns tuple of items to compare with