Working with Dictionary in Python for Competitive Programming - Advanced

In the previous post, we learnt

  • how to create a Dictionary using to lists of same length
  • how to create a Dictionary using dictionary comprehension in Python
  • how to iterate through a Dictionary in Python
  • how to obtain list of keys of a Dictionary in Python
  • how to obtain list of values of a Dictionary in Python
  • how to reverse iterate through a Dictionary in Python
  • how to swap keys with values and Vice Versa of a dictionary in Python

In this post, we will learn

  • how to sort a Dictionary in the ascending order of Keys in Python
  • how to sort a Dictionary in the descending order of Keys in Python
  • how to sort a Dictionary in the ascending order of Values in Python
  • how to sort a Dictionary in the descending order of Values in Python

Sort a Dictionary in the ascending order of Keys in Python

A dictionary can be sorted by keys in the ascending order using sorted method in Python.

We will look at the various approaches to sort a dictionary by keys in ascending order in Python.

Approach 1: Sort a dictionary in the ascending order of keys using sorted() and for loop in Python

To sort a dictionary using sorted() method and for loop, we will have the following steps:

  • First we initialize a resultant dictionary which will have key value pair in sorted order.
  • Then we sort the keys of a dictionary in ascending order using sorted().
  • Then we iterate over the sorted keys using for loop.
  • Then we add each key value pair to the resultant dictionary.

The following code will demonstrates sorting a dictionary in the ascending order of keys in Python.

d1 = {'Bob': 60, 'Alice': 43, 'Ram': 80, 'Geeta': 49, 'Shreyan': 95, 'Raj': 68}
sorted_d1 = dict()

for key in sorted(d1.keys(), reverse = False):
    sorted_d1[key] = d1[key]

print(sorted_d1)

Sort a dictionary in the ascending order of keys using sorted() and for loop in Python

Notice that the sorted method takes two arguments, where the second one is optional.

  • The first argument must be of type list. Here we are passing d1.keys() as input to the first argument of sorted() method.
  • The second argument is the reverse, by default, it is False. This means, the elements will be sorted in the ascending order. When reverse is set to True, the list elements provided in the first argument, which in our case is d1.keys() will be sorted in the descending order.
  • The sorted method returns the list after sorting the input list based on the reverse argument.

The output of the preceding code will be as follows.

{'Alice': 43, 'Bob': 60, 'Geeta': 49, 'Raj': 68, 'Ram': 80, 'Shreyan': 95}

Output: Sort a dictionary in the ascending order of keys using sorted() and for loop in Python

We notice that the resultant dictionary has the keys in the ascending order with their respective values. We also notice that after sorting a dictionary by key, the results shows the students in the ascending order of marks.

Approach 2: Sort a dictionary in the ascending order of keys using list comprehension and sorted in Python

We can also sort a dictionary by ascending order of keys using the same sorted method, but this time using list comprehension.

d1 = {'Bob': 60, 'Alice': 43, 'Ram': 80, 'Geeta': 49, 'Shreyan': 95, 'Raj': 68}
sorted_d1 = { key:d1[key] for key in sorted(d1.keys(), reverse = False)}
print(sorted_d1)

Sort a dictionary in the ascending order of keys using list comprehension and sorted in Python

This approach is similar to Approach 1, but instead of for loop, the Approach 2 uses list comprehension to sort a dictionary in the ascending order of keys. The output of the preceding code will be as follows.

{'Alice': 43, 'Bob': 60, 'Geeta': 49, 'Raj': 68, 'Ram': 80, 'Shreyan': 95}

Output: Sort a dictionary in the ascending order of keys using list comprehension and sorted in Python

We notice that the resultant dictionary has the keys in the ascending order with their respective values. We also notice that after sorting a dictionary by key, the results shows the students in the ascending order of marks.

Approach 3: Sort a dictionary in the ascending order of keys using dict(), sorted() and items() in Python

This is the simple one liner approach that creates a sorted version of the dictionary whose keys are in the ascending order.

d1 = {'Bob': 60, 'Alice': 43, 'Ram': 80, 'Geeta': 49, 'Shreyan': 95, 'Raj': 68}
sorted_d1 = dict(sorted(d1.items()))
print(sorted_d1)

Sort a dictionary in the ascending order of keys using list comprehension and sorted in Python

From the preceding code, we notice that we are first getting a list of items as key value tuples returned by d1.items(). The resultant list is passed as an argument to the sorted() method which returns a list of tuples in the form of (key, value). This is fed to the dict() which takes list of tuple. The resultant dictionary is assigned to sorted_d1. Hence, the output of the preceding code will be as follows.

{'Alice': 43, 'Bob': 60, 'Geeta': 49, 'Raj': 68, 'Ram': 80, 'Shreyan': 95}

Sort a dictionary in the ascending order of keys using list comprehension and sorted in Python

We notice that the resultant dictionary has the keys in the ascending order with their respective values. We also notice that after sorting a dictionary by key, the results shows the students in the ascending order of marks.

Approach 4: Sort a dictionary in the ascending order of keys using sorted(), lambda and dictionary comprehension in Python

In this approach, we will do the following to sort a dictionary in the ascending order of keys using sorted(), items() and dictionary comprehension.

d1 = {'Bob': 60, 'Alice': 43, 'Ram': 80, 'Geeta': 49, 'Shreyan': 95, 'Raj': 68}
sorted_by_keys = {k: v for k, v in sorted(d1.items(), key=lambda item: item[0], reverse = False)}

print('Before sort')
print(d1)
print('After sort by keys in ascending order using dictionary comprehension')
print(sorted_by_keys)

Sort a dictionary in the ascending order of keys using sorted(), lambda and dictionary comprehension in Python

Here, in the preceding code, we are sorting a dictionary by its ascending order of keys in Python using dictionary comprehension, sorted() and lambda.

We notice that the sorted method is provided with two arguments,

  • The first argument is the list of tuples represented by d1.items().
  • Each item in the list of tuple let's say is represented by variable name item. Then the item is of type tuple and each element in a tuple is accessed by it's index position. In case of key and value being the items of item tuple, the element at index 0, represented by item[0] is key and the element at index 1 represented by item[1] is the value.
  • Hence, the second argument to the sorted method, key is specifying to the sorted method to perform the sort operation based on the item[0] which is the keys amongst the key value pair.
  • As we need to sort by ascending order of keys, we have also provided the keyword argument reverse set to False as input to sorted method.

The output of the preceding code will be as follows.

Before sort
{'Bob': 60, 'Alice': 43, 'Ram': 80, 'Geeta': 49, 'Shreyan': 95, 'Raj': 68}
After sort by keys in ascending order using dictionary comprehension
{'Alice': 43, 'Bob': 60, 'Geeta': 49, 'Raj': 68, 'Ram': 80, 'Shreyan': 95}

Output: Sort a dictionary in the ascending order of keys using sorted(), lambda and dictionary comprehension in Python

We notice that the resultant dictionary has the keys in the ascending order with their respective values. We also notice that after sorting a dictionary by key, the results shows the students in the ascending order of marks.

Sort a Dictionary in the descending order of Keys in Python

A dictionary can be sorted by keys in the descending order using sorted method in Python.

We will look at the various approaches to sort a dictionary by keys in descending order in Python.

Approach 1: Sort a dictionary in the descending order of keys using sorted() and for loop in Python

To sort a dictionary using sorted() method and for loop, we will have the following steps:

  • First we initialize a resultant dictionary which will have key value pair in sorted order.
  • Then we sort the keys of a dictionary in descending order using sorted().
  • Then we iterate over the sorted keys using for loop.
  • Then we add each key value pair to the resultant dictionary.

The following code will demonstrates sorting a dictionary in the descending order of keys in Python.

d1 = {'Bob': 60, 'Alice': 43, 'Ram': 80, 'Geeta': 49, 'Shreyan': 95, 'Raj': 68}
sorted_d1 = dict()

for key in sorted(d1.keys(), reverse = True):
    sorted_d1[key] = d1[key]

print(sorted_d1)

Sort a dictionary in the descending order of keys using sorted() and for loop in Python

Notice that the sorted method takes two arguments, where the second one is optional.

  • The first argument must be of type list. Here we are passing d1.keys() as input to the first argument of sorted() method.
  • The second argument is the reverse, by default, it is False. This means, the elements will be sorted in the descending order. When reverse is set to True, the list elements provided in the first argument, which in our case is d1.keys() will be sorted in the descending order.
  • The sorted method returns the list after sorting the input list based on the reverse argument.

The output of the preceding code will be as follows.

{'Shreyan': 95, 'Ram': 80, 'Raj': 68, 'Geeta': 49, 'Bob': 60, 'Alice': 43}

Output: Sort a dictionary in the descending order of keys using sorted() and for loop in Python

We notice that the resultant dictionary has the keys in the descending order with their respective values. We also notice that after sorting a dictionary by key, the results shows the students in the descending order of marks.

Approach 2: Sort a dictionary in the descending order of keys using list comprehension and sorted in Python

We can also sort a dictionary by descending order of keys using the same sorted method, but this time using list comprehension.

d1 = {'Bob': 60, 'Alice': 43, 'Ram': 80, 'Geeta': 49, 'Shreyan': 95, 'Raj': 68}
sorted_d1 = { key:d1[key] for key in sorted(d1.keys(), reverse = True)}
print(sorted_d1)

Sort a dictionary in the descending order of keys using list comprehension and sorted in Python

This approach is similar to Approach 1, but instead of for loop, the Approach 2 uses list comprehension to sort a dictionary in the descending order of keys. The output of the preceding code will be as follows.

{'Shreyan': 95, 'Ram': 80, 'Raj': 68, 'Geeta': 49, 'Bob': 60, 'Alice': 43}

Output: Sort a dictionary in the descending order of keys using list comprehension and sorted in Python

We notice that the resultant dictionary has the keys in the descending order with their respective values. We also notice that after sorting a dictionary by key, the results shows the students in the descending order of marks.

Approach 3: Sort a dictionary in the descending order of keys using dict(), sorted() and items() in Python

This is the simple one liner approach that creates a sorted version of the dictionary whose keys are in the descending order.

d1 = {'Bob': 60, 'Alice': 43, 'Ram': 80, 'Geeta': 49, 'Shreyan': 95, 'Raj': 68}
sorted_d1 = dict(sorted(d1.items(), reverse = True))
print(sorted_d1)

Sort a dictionary in the descending order of keys using list comprehension and sorted in Python

From the preceding code, we notice that we are first getting a list of items as key value tuples returned by d1.items(). The resultant list is passed as an argument to the sorted() method which returns a list of tuples in the form of (key, value). We also set the reversed to True as we are expecting the dictionary items to be in the descending order of keys. The reversed list of tuples is then fed as input argument to the dict() which takes list of tuple. The resultant dictionary is assigned to sorted_d1. Hence, the output of the preceding code will be as follows.

{'Shreyan': 95, 'Ram': 80, 'Raj': 68, 'Geeta': 49, 'Bob': 60, 'Alice': 43}

Sort a dictionary in the descending order of keys using list comprehension and sorted in Python

We notice that the resultant dictionary has the keys in the descending order with their respective values. We also notice that after sorting a dictionary by key, the results shows the students in the descending order of marks.

Approach 4: Sort a dictionary in the descending order of keys using sorted(), lambda and dictionary comprehension in Python

In this approach, we will do the following to sort a dictionary in the descending order of keys using sorted(), items() and dictionary comprehension.

d1 = {'Bob': 60, 'Alice': 43, 'Ram': 80, 'Geeta': 49, 'Shreyan': 95, 'Raj': 68}
sorted_by_keys = {k: v for k, v in sorted(d1.items(), key=lambda item: item[0], reverse = True)}

print('Before sort')
print(d1)
print('After sort by keys in descending order using dictionary comprehension')
print(sorted_by_keys)

Sort a dictionary in the descending order of keys using sorted(), lambda and dictionary comprehension in Python

Here, in the preceding code, we are sorting a dictionary by its descending order of keys in Python using dictionary comprehension, sorted() and lambda.

We notice that the sorted method is provided with two arguments,

  • The first argument is the list of tuples represented by d1.items().
  • Each item in the list of tuple let's say is represented by variable name item. Then the item is of type tuple and each element in a tuple is accessed by it's index position. In case of key and value being the items of item tuple, the element at index 0, represented by item[0] is key and the element at index 1 represented by item[1] is the value.
  • Hence, the second argument to the sorted method, key is specifying to the sorted method to perform the sort operation based on the item[0] which is the keys amongst the key value pair.
  • As we need to sort by descending order of keys, we have also provided the keyword argument reverse set to True as input argument to sorted method.

The output of the preceding code will be as follows.

Before sort
{'Bob': 60, 'Alice': 43, 'Ram': 80, 'Geeta': 49, 'Shreyan': 95, 'Raj': 68}
After sort by keys in descending order using dictionary comprehension
{'Shreyan': 95, 'Ram': 80, 'Raj': 68, 'Geeta': 49, 'Bob': 60, 'Alice': 43}

Output: Sort a dictionary in the descending order of keys using sorted(), lambda and dictionary comprehension in Python

We notice that the resultant dictionary has the keys in the descending order with their respective values. We also notice that after sorting a dictionary by key, the results shows the students in the descending order of marks.

Sort a Dictionary in the ascending order of Values Python

A dictionary can be sorted by values in the ascending order using sorted method in Python.

We will look at the various approaches to sort a dictionary by values in ascending order in Python.

Approach 1: Sort a dictionary in the ascending order of values using sorted(), items() and for loop in Python

In this approach, we will do the following to sort a dictionary in the ascending order of values using sorted(), items() and for loop.

d1 = {'Bob': 60, 'Alice': 43, 'Ram': 80, 'Geeta': 49, 'Shreyan': 95, 'Raj': 68}
sorted_by_values = dict()
tup = list()
for k, v in d1.items():
    tup.append((v, k))

for v, k in sorted(tup):
    sorted_by_values[k] = v

print('Before sort')
print(d1)
print('After sorting a dictionary by its value in ascending order')
print(sorted_by_values)

Sort a dictionary in the ascending order of values using sorted(), items() and for loop in Python

In the preceding code, we perform the following steps in the order described below.

  • First we define a resultant dictionary that will hold the key value pairs whose order will be in the ascending order of values.
  • We then define a list in which we will maintain tuples of key value pair of dictionary
  • We then iterate over dictionary using items() and add value and then key pair as tuples to the list.
  • We then perform sort over the list of tuples having value and key pairs.
  • We finally iterate over the sorted list of tuples and add the value key pair to the resultant dictionary by mapping second item in the tuple as key and first item in the tuple as value.

The output of the preceding code will be as follows.

Before sort
{'Bob': 60, 'Alice': 43, 'Ram': 80, 'Geeta': 49, 'Shreyan': 95, 'Raj': 68}
After sorting a dictionary by its value in ascending order
{'Alice': 43, 'Geeta': 49, 'Bob': 60, 'Raj': 68, 'Ram': 80, 'Shreyan': 95}

Output: Sort a dictionary in the ascending order of values using sorted(), items() and for loop in Python

We notice that the resultant dictionary has the values in the ascending order with their respective values. We also notice that after sorting a dictionary by value, the results shows the students in the ascending order of marks.

Approach 2: Sort a dictionary in the ascending order of values using sorted(), lambda and dictionary comprehension in Python

In this approach, we will do the following to sort a dictionary in the ascending order of values using sorted(), items() and dictionary comprehension.

d1 = {'Bob': 60, 'Alice': 43, 'Ram': 80, 'Geeta': 49, 'Shreyan': 95, 'Raj': 68}
sorted_by_values = {k: v for k, v in sorted(d1.items(), key=lambda item: item[1])}

print('Before sort')
print(d1)
print('After sorting a dictionary by its value in ascending order using dictionary comprehension')
print(sorted_by_values)

Sort a dictionary in the ascending order of values using sorted(), lambda and dictionary comprehension in Python

Here, in the preceding code, we are sorting a dictionary by its ascending order of values in Python using dictionary comprehension, sorted() and lambda.

We notice that the sorted method is provided with two arguments,

  • The first argument is the list of tuples represented by d1.items().
  • Each item in the list of tuple let's say is represented by variable name item. Then the item is of type tuple and each element in a tuple is accessed by it's index position. In case of key and value being the items of item tuple, the element at index 0, represented by item[0] is key and the element at index 1 represented by item[1] is the value.
  • Hence, the second argument to the sorted method, key is specifying to the sorted method to perform the sort operation based on the item[1] which is the value amongst the key value pair.

The output of the preceding code will be as follows.

Before sort
{'Bob': 60, 'Alice': 43, 'Ram': 80, 'Geeta': 49, 'Shreyan': 95, 'Raj': 68}
After sorting a dictionary by its value in ascending order using dictionary comprehension
{'Alice': 43, 'Geeta': 49, 'Bob': 60, 'Raj': 68, 'Ram': 80, 'Shreyan': 95}

Output: Sort a dictionary in the ascending order of values using sorted(), lambda and dictionary comprehension in Python

We notice that the resultant dictionary has the values in the ascending order with their respective values. We also notice that after sorting a dictionary by value, the results shows the students in the ascending order of marks.

Sort a Dictionary in the descending order of Values Python

A dictionary can be sorted by values in the descending order using sorted method in Python.

We will look at the various approaches to sort a dictionary by values in descending order in Python.

Approach 1: Sort a dictionary in the descending order of values using sorted(), items() and for loop in Python

In this approach, we will do the following to sort a dictionary in the descending order of values using sorted(), items() and for loop.

d1 = {'Bob': 60, 'Alice': 43, 'Ram': 80, 'Geeta': 49, 'Shreyan': 95, 'Raj': 68}
sorted_by_values = dict()
tup = list()
for k, v in d1.items():
    tup.append((v, k))

for v, k in sorted(tup, reverse = True):
    sorted_by_values[k] = v

print('Before sort')
print(d1)
print('After sort by value in descending order')
print(sorted_by_values)

Sort a dictionary in the ascending order of values using sorted(), items() and for loop in Python

In the preceding code, we perform the following steps in the order described below.

  • First we define a resultant dictionary that will hold the key value pairs whose order will be in the descending order of values.
  • We then define a list in which we will maintain tuples of key value pair of dictionary
  • We then iterate over dictionary using items() and add value and then key pair as tuples to the list.
  • We then perform sort over the list of tuples having value and key pairs.
  • We finally iterate over the sorted list of tuples and add the value key pair to the resultant dictionary by mapping second item in the tuple as key and first item in the tuple as value.
  • As we need to sort by descending order of values, we have also provided the keyword argument reverse set to True as input argument to sorted method.

The output of the preceding code will be as follows.

Before sort
{'Bob': 60, 'Alice': 43, 'Ram': 80, 'Geeta': 49, 'Shreyan': 95, 'Raj': 68}
After sort by value in descending order
{'Shreyan': 95, 'Ram': 80, 'Raj': 68, 'Bob': 60, 'Geeta': 49, 'Alice': 43}

Output: Sort a dictionary in the descending order of values using sorted(), items() and for loop in Python

We notice that the resultant dictionary has the values in the descending order with their respective values. We also notice that after sorting a dictionary by value, the results shows the students in the descending order of marks.

Approach 2: Sort a dictionary in the descending order of values using sorted(), lambda and dictionary comprehension in Python

In this approach, we will do the following to sort a dictionary in the descending order of values using sorted(), items() and dictionary comprehension.

d1 = {'Bob': 60, 'Alice': 43, 'Ram': 80, 'Geeta': 49, 'Shreyan': 95, 'Raj': 68}
sorted_by_values = {k: v for k, v in sorted(d1.items(), key=lambda item: item[1], reverse = True)}

print('Before sort')
print(d1)
print('After sort by value in descending order using dictionary comprehension')
print(sorted_by_values)

Sort a dictionary in the descending order of values using sorted(), lambda and dictionary comprehension in Python

Here, in the preceding code, we are sorting a dictionary by its descending order of values in Python using dictionary comprehension, sorted() and lambda.

We notice that the sorted method is provided with two arguments,

  • The first argument is the list of tuples represented by d1.items().
  • Each item in the list of tuple let's say is represented by variable name item. Then the item is of type tuple and each element in a tuple is accessed by it's index position. In case of key and value being the items of item tuple, the element at index 0, represented by item[0] is key and the element at index 1 represented by item[1] is the value.
  • Hence, the second argument to the sorted method, key is specifying to the sorted method to perform the sort operation based on the item[1] which is the value amongst the key value pair.
  • As we need to sort by descending order of values, we have also provided the keyword argument reverse set to True as input argument to sorted method.

The output of the preceding code will be as follows.

Before sort
{'Bob': 60, 'Alice': 43, 'Ram': 80, 'Geeta': 49, 'Shreyan': 95, 'Raj': 68}
After sort by value in descending order using dictionary comprehension
{'Shreyan': 95, 'Ram': 80, 'Raj': 68, 'Bob': 60, 'Geeta': 49, 'Alice': 43}

Output: Sort a dictionary in the descending order of values using sorted(), lambda and dictionary comprehension in Python

We notice that the resultant dictionary has the values in the descending order with their respective values. We also notice that after sorting a dictionary by value, the results shows the students in the descending order of marks.