I've got a list of dicts which describe certain classes in a school of which some are still taught, some are not anymore, and some are going to be taught in the future:
[
{'status': 'DEACTIVE', 'name': 'Music'},
{'status': 'DEACTIVE', 'name': 'Juggling'},
{'status': 'ACTIVE', 'name': 'Chess'},
{'status': 'ACTIVE', 'name': 'Dutch Language'},
{'status': 'COMING', 'name': 'Python'},
{'status': 'COMING', 'name': 'Drinking coffee like a pro'},
]
I now want to order this list so that the ACTIVE
are first, then the DEACTIVE
, and finally the COMING
. I found solutions such as this:
sorted(a, key=dict.values, reverse=True)
but that only orders it by alphabet where I want to sort it in a custom way. Does anybody know how I can do this?
You can do it using dictionary with weight of all statuses:
STATUS_RANK = {"ACTIVE": 1, "DEACTIVE": 2, "COMING": 3}
courses.sort(key=lambda x: STATUS_RANK[x['status']])
i just made a method to handle that called it order_my_list() as you see below: all you need is just to pass your list as a parameter!
def order_my_list(lst):
ordered = []
loop = 0
finished_flag = 0
while finished_flag == 0:
for x in range(0,len(lst)):
if loop == 0:
if lst[x]['status'] == 'ACTIVE':
ordered.append(lst[x])
if loop == 1:
if lst[x]['status'] == 'DEACTIVE':
ordered.append(lst[x])
if loop == 2:
if lst[x]['status'] == 'COMING':
ordered.append(lst[x])
if loop == 3:
finished_flag = 1
loop += 1
return ordered
Im sure there is better/faster ways to do it but thats how i would solve it as my python knowledge isnt that great :p ...
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.