2

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]

1
  • 1
    I didnt get ur question ...do you want to sort the list according to its values fron the dict or what ?? Commented Mar 4, 2016 at 7:04

1 Answer 1

5

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]
Sign up to request clarification or add additional context in comments.

3 Comments

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 ?
@SagarR Sorry I can't get you, pleas add your explanation to the question.
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

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.