I have searched that we can sort a list of dictionary by key in alphabetical order using sorted, but is it to sort it in custom order?
for example:
alist = [
{"id":"A","day":"sun"},
{"id":"B","day":"tue"},
{"id":"C","day":"mon"}
]
sort alist according to "day" in custom order i.e. "sun", "mon", "tue"...."sat"
sortedalist = [
{"id":"A","day":"sun"},
{"id":"C","day":"mon"}
{"id":"B","day":"tue"}
]
how can I do this? I think lambda expression is needed to be the key in sorted(), but I am not sure what should be the function
You can define a custom sort order in a dict
sortorder={"sun":0, "mon":1, "tue":2, "wed":3, "thu":4, "fri":5, "sat":6}
and then use this in the sort function:
my_list.sort(key=lambda x: sortorder[x["day"]])
This sorts the list inplace without returning a copy.
If you need a copy of the list which is sorted, then you can use
sorted_list=sorted(my_list, key=lambda x: sortorder[x["day"]])
In the original question, the variable name of the list was called list
. Notice that it is bad practice to call a list list
because python internals are overwritten with this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With