10
order = ['w','x','a','z']
[(object,'a'),(object,'x'),(object,'z'),(object,'a'),(object,'w')]

How do I sort the above list of tuples by the second element according the the key list provided by 'order'?

UPDATE on 11/18/13:

I found a much better approach to a variation of this question where the keys are certain to be unique, detailed in this question: Python: using a dict to speed sorting of a list of tuples.

My above question doesn't quite apply because the give list of tuples has two tuples with the key value of 'a'.

1
  • Can you give an example of what you are expecting the result to look like? Commented Nov 16, 2012 at 1:07

1 Answer 1

13

You can use sorted, and give as the key a function that returns the index of the second value of each tuple in the order list.

>>> sorted(mylist,key=lambda x: order.index(x[1]))

[('object', 'w'), ('object', 'x'), ('object', 'a'), ('object', 'a'), ('object', 'z')]

Beware, this fails whenever a value from the tuples is not present within the order list.

Edit:

In order to be a little more secure, you could use :

sorted(mylist,key=lambda x: x[1] in order and order.index(x[1]) or len(order)+1)

This will put all entries with a key that is missing from order list at the end of the resulting list.

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

1 Comment

That last edit was very helpful because now I can let the sort fail in a very elegant way. Thanks!

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.