
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort a Dictionary in Python by Values
Standard distribution of Python contains collections module. It has definitions of high performance container data types. OrderedDict is a sub class of dictionary which remembers the order of entries added in dictionary object. When iterating over an ordered dictionary, the items are returned in the order their keys were first added.
>>> from collections import OrderedDict >>> D = {5:'fff', 3:'ttt', 1:'ooo',4:'bbb', 2:'ddd'} >>> OrderedDict(D.items()) OrderedDict([(5, 'fff'), (3, 'ttt'), (1, 'ooo'), (4, 'bbb'), (2, 'ddd')])
We also need to us sorted() function that sorts elements in an iterable in a specified order. The function takes a function as argument which is used as key for sorting. Since we intend to sort dictionary on values, we take 1st element of tuple as key for sorting.
>>> OrderedDict(sorted(D.items(), key=lambda t: t[1])) OrderedDict([(4, 'bbb'), (2, 'ddd'), (5, 'fff'), (1, 'ooo'), (3, 'ttt')])
The OrderedDict object can be parsed into a regular dictionary object
>>> D1 = dict(OrderedDict(sorted(D.items(), key = lambda t: t[1]))) >>> D1 {4: 'bbb', 2: 'ddd', 5: 'fff', 1: 'ooo', 3: 'ttt'}
Advertisements