3

I am trying to sort a list of tuples based on another list of tuples by a key in that list.

Say I have the following:

list1 = [(5, 'something'),(2,'bobby'),(9,'suzy'),(6,'crab')]
list2 = [('something','othervalues'),('suzy','stuff'),('bobby','otherthings')]

And from this I would receive the output soring on the first element of each tuple in list1.

sorted = [('suzy','stuff'),('something','othervalues'),('bobby','otherthings') ]

So essentially it performs an intersection and then sorts on the remaining values by the first element in the tuple of list1.

I am not sure how to go about this, so any help would be great.

3 Answers 3

3

Just do what the description says, sort a list of tuples based on another list of tuples by a key in that list:

rank = {key:rank for rank, key in list1}
print(sorted(list2, key=lambda t: rank.get(t[0]), reverse=True))
Sign up to request clarification or add additional context in comments.

Comments

3

First create a dictionary from list1:

>>> order = dict(reversed(t) for t in list1)

This creates a name -> number mapping.

Then you can use the sorted method (don't name your variable this way) and a lambda expression as key:

>>> sorted(list2, key=lambda x: order[x[0]], reverse=True)
[('suzy', 'stuff'), ('something', 'othervalues'), ('bobby', 'otherthings')]

or, if you want to sort in-place:

>>> list2.sort(key=lambda x: order[x[0]], reverse=True)

Worth reading: Sorting Mini-HOW TO

Comments

0

This would be easy were list2 a dict, like this:

{'bobby': 'otherthings', 'something': 'othervalues', 'suzy': 'stuff'}

Python will do the conversion for you:

>>> dict2 = dict(list2)

Then you can use a list comprehension:

>>> [(k,dict2[k]) for _,k in sorted(list1, reverse=True) if k in dict2]
[('suzy', 'stuff'), ('something', 'othervalues'), ('bobby', 'otherthings')]

N.B: sorted is a built-in Python function and a bad choice for a variable name.

Comments

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.