Python custom sorting
Question:
I have a list of objects like this:
my_list = [obj1,obj2,obj3, ...]
Each object has some data like:
obj = {
'id':1,
'name':'Some name',
'value': 'Some value',
'category':'A'
}
The category options are: CATEGORY = {'A','B','C','D'}
Is it possible to sort the list somehow to display data in sequence like:
my_sordet_list = ['all in C categ', 'all in B categ', 'all in D categ','all in A categ']
So the question is: How can I explain to the program that I want it to be sorted in a strict custom sequence?
Answers:
You could create a lookup dictionary for your custom ordering:
>>> category_order = {'C': 0, 'B': 1, 'D': 2, 'A': 3}
>>> my_sorted_list = sorted(mylist, key=lambda o: category_order[o['category']])
my_sorted_list
will be sorted, as you desire.
I have a list of objects like this:
my_list = [obj1,obj2,obj3, ...]
Each object has some data like:
obj = {
'id':1,
'name':'Some name',
'value': 'Some value',
'category':'A'
}
The category options are: CATEGORY = {'A','B','C','D'}
Is it possible to sort the list somehow to display data in sequence like:
my_sordet_list = ['all in C categ', 'all in B categ', 'all in D categ','all in A categ']
So the question is: How can I explain to the program that I want it to be sorted in a strict custom sequence?
You could create a lookup dictionary for your custom ordering:
>>> category_order = {'C': 0, 'B': 1, 'D': 2, 'A': 3}
>>> my_sorted_list = sorted(mylist, key=lambda o: category_order[o['category']])
my_sorted_list
will be sorted, as you desire.