0

I have a python list which I want to order. I can only think of one way todo this so far which is to have a dictionary and according to that dictionary value depends on the position.

How can I do this better?

These are the values

>>> a = ['Extra large', 'Large', 'Small', 'Medium', 'Extra Small']
>>> b = ['XL', 'XS', 'XXXL', 'L', 'M']

What i want to be able to produce

>>> a = ['Extra Small', 'Small', 'Medium', 'Large', 'Extra large']
>>> b = ['XS', 'XL', 'M', 'L', 'XXXL']

I was thinking of having a diction like this but i'm sure there is a better way todo it that looping through each value?

size_mapping = {
    0: ['small', 's'],
    1: ['medium', 'm'],
    2: ['large', 'l']
}
1
  • i would use sets instead of list in the dictionary Commented Dec 22, 2015 at 11:21

2 Answers 2

3

For this particular set of items, you’re better off sorting them manually, and just storing them sorted somewhere in your application:

sizes = ['XS', 'S', 'M', 'L', 'XL', 'XXL', 'XXXL']

After all, those sizes come from a fixed set, so it’s not like you will run into problems with sudden new sizes.

Every automated way to sort them would require you to express this exact order in some way. Yes, you could tell the sorter that S is smaller than M is smaller than L and that X-something is more small or large than just something, but express that logic dynamically can quickly get rather complicated. And all other alternatives also require that you essentially just encode that exact order above in some way. So you gain nothing except confusion and chance for bugs if you do it another way.


Note that you can use above list to sort subsets of that list. As an example, let’s assume you have a shop which sells shirts, and one particular shirt only comes in the sizes L, S, XL, and M. In order to tell the customer which sizes are there, we want to display these—but in the proper order, so we can do the following:

available_sizes = ['L', 'S', 'XL', 'M']
print(available_sizes) # ['L', 'S', 'XL', 'M']

# sort them using the existing sorted list of possible sizes
available_sizes.sort(key=lambda size: sizes.index(size))
print(available_sizes) # ['S', 'M', 'L', 'XL']
Sign up to request clarification or add additional context in comments.

Comments

1

This approach will do

>>> to_sort = ["M","XS","S","L","XL"]
>>> size_d = {"XS":0,"S":1,"M":2,"L":3,"XL":4}
>>> sorted_list = sorted(to_sort, key=lambda x:size_d.get(x,0))
>>> sorted_list
['XS', 'S', 'M', 'L', 'XL']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.