

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
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
How to 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'}
- Related Questions & Answers
- How to sort a Python dictionary by value?
- How to sort a Python dictionary by datatype?
- How to sort a dictionary in Python by keys?
- How to sort a dictionary in Python?
- How do I sort a list of dictionaries by values of the dictionary in Python?
- How to sort a nested Python dictionary?
- Sort Dictionary key and values List in Python
- How to update a Python dictionary values?
- How to replace values in a Python dictionary?
- How to sum values of a Python dictionary?
- How to replace values of a Python dictionary?
- Java Program to Sort a Map By Values
- Ways to sort list of dictionaries by values in Python
- How to sort a boxplot by the median values in Pandas?
- How to sort Map values by key in Java?
Advertisements