Sort Dictionary in Python
Dictionaries
In Python, a dictionary is an unordered collection or set of data types that enable of store data in an unordered key-value/pair. The key is stored alongside with value.
Dictionary contains key: value pair that provides which makes it more optimized.
A dictionary is defined with a comma-separated list of Key-Value pairs enclosed with curly braces {}. Keys and values are separated with a colon (:) between other keys and values in the dictionary.
Need for sorting the dictionary
When the amount of data is too large, it is very difficult to handle the large data quickly and effectively. Sorting can remove the problem of handling a large amount of data. Sorting can reduce the complexity of data collection.
In Python, we can sort a dictionary by Keys and Values.
Sorting Dictionary by Key in Python
When a dictionary is sorted by key, it returns a list that contains tuples of key-value pairs. For example, {"b": 5, "c": 4, "a": 6} returns [("a", 6), ("b", 5), ("c", 4)].
We can perform sorting with only the sorted() function and also we can do it with for loop, lambda function, and dict.items() method.
Syntax:
sorted(iterable, key, reverse)
Here, we are using dict.items() with sorted() method for sorting a dictionary. It gives a list of tuples sorted by a key.
Example 1: Using dict.items()
A dictionary can be sorted by using dict.items() method. The dictionary is ordered for the sorted() method and then performs sorting with dict.items() method.
# Code to sort a dictionary by key
# using dict.items()
from collections import OrderedDict
dict = {'ramesh':'30','Akash':'10,'sanjay':'20','Umesh':'40','deepak':'50'}
dict1 = OrderedDict(sorted(dict.items()))
print(dict1)
Output:
OrderedDict([('Akash', '10'), ('Umesh', '40'), ('deepak', '50'), ('ramesh', '30'), ('sanjay', '20')])
Example 2: Using for Loop
The dictionary sorting using keys can also be done by using for loop and keys() method. The keys() method separates the keys from the dictionary and sorting can be done by using for loop.
# Code to sort a dictionary by key
# using for loop
from collections import OrderedDict
dictionary = {'Elice':'3','Ronny':'56','Rushel':'34','Jhon':'33','Rose':'22'}
sorted_keys = sorted(dictionary.keys())
sorted_dict = {key:dictionary[key] for key in sorted_keys}
print(sorted_dict)
Output:
{'Rose': '22', 'Elice': '3', 'Jhon': '33', 'Ronny': '56', 'Rushel': '34'}
Example 3: Using sorted() method
By using the sorted() method, we can also sort a dictionary. The sorted() method is utilized for the given dictionary and it will be sort using for loop.
The sorted() method is used to perform the sorting operation. It allows three parameters: the iterable, the key, and the reverse.
# Code to sort a dictionary by key
# using sorted()
from collections import OrderedDict
dictionary = {'Elice':'3','Ronny':'56','Rushel':'34','Jhon':'33','Rose':'22'}
dictionary1 = sorted(dictionary)
sorted_dict = {key:dictionary[key] for key in dictionary1}
print(sorted_dict)
Output:
{'Ronny': '56', 'Rose': '22', 'Elice': '3', 'Jhon': '33', 'Rushel': '34'}
Sort Dictionary By Value
As we sorted the dictionary with keys, similarly we can perform sorting with the values in the dictionary by using multiple methods. If we sort a dictionary with the values it returns a sorted dictionary.
We can perform sorting with only the sorted() function and also we can do it with for loop, lambda function, and dictionary.items() method.
Example 1: Using for loop
The dictionary sorting using keys can also be done by using for loop and sorted() method. In this method, values of the dictionary are ordered using the sorted() function and then find the keys of every value with for loop.
# Code to sort a dictionary by value
# using for loop
from collections import OrderedDict
dic = {'Elice':'3','Ronny':'56','Rushel':'34','Jhon':'33','Rose':'22'}
print("Given dictionary : ",dic)
sorted_values = sorted(dic.values())
# Sort the values
sorted_dict = {}
for i in sorted_values:
for k in dic.keys():
if dic[k] == i:
sorted_dict[k] = dic[k]
break
#printing sorted dictionary
print("Sorted dictionary : ",sorted_dict)
Output:
Given dictionary : {'Ronny': '56', 'Jhon': '33', 'Elice': '3', 'Rose': '22', 'Rushel': '34'}
Sorted dictionary : {'Rushel': '34', 'Jhon': '33', 'Elice': '3', 'Ronny': '56', 'Rose': '22'}
Example 2: Using dictionary.items() Method
A dictionary can be sorted by using dictionary.items() method. The dictionary is ordered for the sorted() method and then performs sorting by values with dictionary.items() method.
# Code to sort a dictionary by value
# using dictionary.items()
from operator import itemgetter
#given dictionary
dictionary = {'ramesh':'30','Akash':'10','sanjay':'20','Umesh':'40','deepak':'50'}
print("Given Dictionary: ", dictionary)
sort_dict= dict(sorted(dictionary.items(), key=itemgetter(1)))
#printing sorted dictionary
print("Sorted Dictionary : ", sort_dict)
Output:
Given Dictionary: {'deepak': '50', 'ramesh': '30', 'sanjay': '20', 'Umesh': '40', 'Akash': '10'}
Sorted Dictionary : {'ramesh': '30', 'Akash': '10', 'Umesh': '40', 'deepak': '50', 'sanjay': '20'}
Example 3: Using lambda function
Lambda function and sorted() method can also be used together for sorting a dictionary by value in a predefined order in Python. An anonymous function is created by the lambda function that optimizes the code.
# Code to sort a dictionary by value
# using lambda function
dictionary = {'ramesh':'1','Akash':'3','sanjay':'5','Umesh':'4','deepak':'2'}
print("Given Dictionary: ", dictionary)
sort_dictionary= dict(sorted(dictionary.items(), key=lambda item: item[1], reverse = True))
print("Sorted Dictionary : ", sort_dictionary)
Output:
Given Dictionary: {'ramesh': '1', 'Umesh': '4', 'deepak': '2', 'sanjay': '5', 'Akash': '3'}
Sorted Dictionary : {'sanjay': '5', 'ramesh': '1', 'Umesh': '4', 'deepak': '2', 'Akash': '3'}
Conclusion
In this article, We have learned how to perform the sorting of dictionaries in Python. We have seen the different methods of sorting above and understood the use of sorting methods in Python.