0

Given a dictionary:

d = {'a':{'priority': 10}, 'b': {'priority':20}} 

Can I return the keys in a sorted order by priority (in a dict in the value)?

Something like:

>>> print sorted_list ['b', 'a'] 
2
  • 1
    do you need to sort with respect to priority or will there be any other keys Commented Nov 17, 2015 at 14:17
  • Sorry, there are other keys, but priority will be the one I sort on. Commented Nov 17, 2015 at 14:45

2 Answers 2

6

Sure.

sorted_list = sorted(d.keys(), key=lambda i: d[i]['priority'], reverse=True) 
Sign up to request clarification or add additional context in comments.

1 Comment

I knew lambda would be the key... Looking that up now... Thanks
6

By giving sorted a key to sort by, in this case 'priority'

sorted(d, key=lambda e: d[e]['priority'], reverse=True) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.