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?

Asked By: Kirill Kriachenko

||

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.

Answered By: Sash Sinha
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.