Reputation: 35
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.
Upvotes: 3
Views: 889
Reputation: 141810
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.
Upvotes: 0
Reputation: 414235
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))
Upvotes: 3
Reputation: 816442
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
Upvotes: 3