-1

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?

0

1 Answer 1

-1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.