I have a dict y = {6:34,5:40,3:70,2:80} and list m = [5,2,3] which has only some keys of dict y. I have to sort based on values of dict y = {2:80,3:70,5:40,6:34} and only consider keys present in list m and final result should have sorted m =[2,3,5]
-
1I didnt get ur question ...do you want to sort the list according to its values fron the dict or what ??Dark Matter– Dark Matter2016-03-04 07:04:39 +00:00Commented Mar 4, 2016 at 7:04
Add a comment
|
1 Answer
You can use sorted() with a key function which will sort your list based on your dictionary values:
>>> sorted(m, key= lambda x: -y.get(x))
[2, 3, 5]
Note that since sorted() sorts the items in ascending mode you can use negative value of the dict values to make it sort your list descending. Or you could change the reverse argument to True:
>>> sorted(m, key= lambda x: y.get(x), reverse=True)
[2, 3, 5]
3 Comments
FryMan
if i have method sort(m,y) i should sort it on the same reference m... so inside method if i do print "Before",m and call sorted(m, key= lambda x: y.get(x), reverse=True) and call print "After",m m should be sorted on the same reference......How do i do it ?
Kasravnd
@SagarR Sorry I can't get you, pleas add your explanation to the question.
FryMan
In below code when i call print "After Sorting ", m... it should print [2, 3, 5] Not [5, 2, 3] How do i do it ?? import operator def sorting(y,m): sorted(m, key= lambda x: -y.get(x)) if name == 'main': y = {6:34,5:40,3:70,2:80} m = [5,2,3] print "Before Sorting ", m sorting(y,m) print "After Sorting ", m