Reputation: 5894
I have a List of strings named frequentItems
and a Dict named mis
(Multiple Item Support value) whose values are floats. The relationship between the two is that any element of frequentItems
, i
is a key to mis
so that mis[frequentItems[i]]
returns a float value.
I would like to sort frequentItems
based on the float values returned from mis[frequentItems[i]]
but am unsure how to specify this using .sort()
or sorted()
. I have basically no experience using lambda
but think it is what I need to specify.
Upvotes: 1
Views: 766
Reputation: 239463
You don't even need the lambda
here, you can simply use dict.get
to get the value corresponding to the elements of the list.
frequentItems.sort(key = mis.get)
Example:
mis, frequentItems = {1: 3.4, 5: 3.14, 3: 7.5}, [1, 3, 5]
frequentItems.sort(key = mis.get)
print(frequentItems) # [5, 1, 3]
Upvotes: 4
Reputation: 113948
def getItem(itemName):
return mis.get(itemName)
frequentItems.sort(key=getItem)
you could of coarse rewrite getItem
as a lambda function
getItem = lambda itemName:mis.get(itemName,None)
frequentItems.sort(key=getItem)
you could include it as key directly as a lambda
frequentItems.sort(key= lambda itemName:mis.get(itemName,None))
you could simplify your argument to a single letter
frequentItems.sort(key= lambda i:mis.get(i,None))
while the lambdas are shorter they can be slower
(or use thefourtheye's much better solution for this actual problem :P)
Upvotes: 1