Suppose that mydict is a dictionary defined by
1 | mydict = {'a': 2, 'c': 5, 'b': 1, 'd': 4} |
Remember that dictionary has no function sort, since it is unordered, not like a list, or tuple.
However, the key function, introduced in version 2.4, is helpful in sorting a dictionary.
To sort by items, and return the keys and items,
1 | sorted( mydict.items(), key=lambda x: x[1] ) |
output:
[('b', 1), ('a', 2), ('d', 4), ('c', 5)]
To return only the keys, sorted by the items,
1 | sorted( mydict.keys(), key=lambda x: mydict[x] ) |
output:
['b', 'a', 'd', 'c']
Note that, adding reverse=True at the end of the sorted function would produce a decending order list.
sorted( mydict.items(), key=lambda x: x[1] )
output:
[('c', 5), ('d', 4), ('a', 2), ('b', 1)]
Happy sorting.
Related Articles:
Popular Articles:
- Backup folders with 7-zip command line
- Insert figures to LaTeX
- Create LaTeX table easily
- Add personal signature to Lotus Notes 7
- Windows XP Service Pack 3 Final release download
Spread/Promote this article.
Digg | Del.icio.us | Stumble | Y! MyWeb | Y! Buzz | Fave It! | RedditSubscribe for free.
Subscribe to Selinap.com feed right now!
Tags: dictionary, Python, sort
