Ordering dictionaries in Python by value and by key using sorted method
Let's learn how to order a Python Dictionary using its values or keys
Dictionary is a very powerful data structure, you will use them in most of your programs during your career. It stores data values like a map. They are an unordered collection of data values and don't hold a single value, It holds key:value pair.
Recap: how to create a Dictionary
Dictionary in python are created within curly {} braces to store a sequence of elements, separated by ‘comma’. This data structure holds a pair of values, one is called the Key and the other corresponding pair element being its Key:value. Values in a dictionary can be of any data type and can be duplicated, whereas keys have to be unique and must be immutable. Dictionary keys are case sensitive, the same name but different cases of Key will be treated as different keys. Be aware of this detail.
In the example below we create two dictionaries, notice that we can use both integers or strings as keys or values:
Dividing and conquering
Dictionary is an unordered data structure, because of this we have to divide our task into some subtasks. Here are the major tasks that are needed to be performed:
First, we create a dictionary and display its keys in order (alphabetically).
Second, we are going to display both the keys and values sorted in alphabetical order by the key.
Finally, we will perform the same as second but sorted in alphabetical order by the value, instead of by the key as before.
First Task
Our first task is to display its key in order. Considering the dictionary created below, we use iterable over keys to print what we want:
After creating the dictionary, we try to print it:
It is not in order as you can see. We are defining the function print_keys_ordered( ) to receive a dictionary as a parameter and print only the key in order( alphabetically).
Second Task
Here we want to print the keys and values in order. To perform this we create a new function, pretty similar to the previous one. We use the key ordered to print also its value.
Third Task
In this task, we want to order the dictionary considering the value.
Notice that the items() method returns all items of a dictionary.
To order it considering the value, we use the parameter key and a lambda function which inverts the keys. The code kv:(kv[1],kv[0]) actually means that the second attribute (value) will be considered first than second(key).
Conclusion
There are many different ways to sort a dictionary, you can use a for loop and create an auxiliary variable to store the ordered dictionary and then print the content. You can use OrderedDict to keep the dictionary in order, and many other options. That is the fun about programming, we always have many ways to achieve the same goal.
Thanks and see you in the next article about Python.