Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python sorting list of dictionary by custom order [duplicate]

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

like image 475
Smelly Potato Avatar asked May 11 '18 17:05

Smelly Potato


1 Answers

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.

like image 72
Merlin1896 Avatar answered Nov 14 '22 03:11

Merlin1896