How to sort a dictionary in python?
A dictionary is a set of unordered key, value pairs. In a dictionary, the keys must be unique and they are stored in an unordered manner.
To build a dictionary separate the key and value pairs by a colon(:). The keys need to be an immutable type i.e. data types for which the keys cannot be changed at runtime such as int, string, tuple, etc. Individual pairs will be separated by a comma(,) and the whole thing will be enclosed in curly braces({…..}).
We can sort a dictionary by using an in built function sorted().
e.g.,
a={1:2, 3:1, 2:3} print(sorted(a.key())) print(sorted(a.items()))
Let us see one more example to understand it more cleary.
a={1:'January', 3:'March', 2:'February', 4:'April'} print(sorted(a.keys())) print(sorted(a.values())) print(sorted(a.items()))
This is all about sorting a dictionary.
Subscribe
Login
Please login to comment
0 Discussion