sort dictionary by value python
Using The sorted(dict1, key=dict1.get) Method.
The sorted() method is an in-built method in Python that is used to sort the elements of an iterable in a specific order (ascending or descending)
- In order to sort the dictionary using the values, we can use the power of the sorted() function.
- We can use the get() method and pass it to the key argument of the sorted() function.
frameworks = { 'VueJS': 2, 'AngularJS': 4, 'Ember': 5, 'ReactJS': 1, 'Svelte': 3 } for each in sorted(frameworks, key=frameworks.get): print(each, frameworks[each])
Output
ReactJS 1 VueJS 2 Svelte 3 AngularJS 4 Ember 5
- In order to sort the dictionary using its values in reverse order, we need to specify the reverse argument as
true
frameworks = { 'VueJS': 2, 'AngularJS': 4, 'Ember': 5, 'ReactJS': 1, 'Svelte': 3 } for each in sorted(frameworks, key=frameworks.get,reverse=True): print(each, frameworks[each])
Output
Ember 5 AngularJS 4 Svelte 3 VueJS 2 ReactJS 1
python sort dictionary by value
Using OrderedDict (For Older Versions Of Python) Method
Dictionaries are generally unordered for versions before Python 3.7, so it is impossible to sort a dictionary directly. Therefore, to overcome this constraint, we need to use the OrderedDict subclass.
- An OrderedDict is a dictionary subclass that preserves the order in which key values are inserted in a dictionary.
- It is included in the collections module in Python.
from collections import OrderedDict frameworks = { 'VueJS': 2, 'AngularJS': 4, 'Ember': 5, 'ReactJS': 1, 'Svelte': 3 } a = OrderedDict(sorted(frameworks.items(), key=lambda x: x[1])) for key,value in a.items(): print(key, value)
Output
('ReactJS', 1) ('VueJS', 2) ('Svelte', 3) ('AngularJS', 4) ('Ember', 5)