How to sort a dictionary in Python?

PythonServer Side ProgrammingProgramming

A dictionary is a data structure that consists of key and value pairs. We can sort a dictionary using two criteria −

Sort by key − The dictionary is sorted in ascending order of its keys. The values are not taken care of.

Sort by value − The dictionary is sorted in ascending order of the values.

Method 1 − Sort the dictionary by key

In this approach, the dictionary is sorted in ascending order of its keys.

Input:

{2:90, 1: 100, 8: 3, 5: 67, 3: 5}

Output:

{1:100, 2:90, 3:5, 5:67, 8:3}

As shown above, we can see the dictionary is sorted according to its keys.

Example

 Live Demo

dic={2:90, 1: 100, 8: 3, 5: 67, 3: 5}
dic2={}
for i in sorted(dic):
   dic2[i]=dic[i]
print(dic2)

Output

{1: 100, 2: 90, 3: 5, 5: 67, 8: 3}

Explanation of code line wise

  • Declare a dictionary which is to be sorted

  • Declare an empty dictionary where sorted key value pairs are to be added

  • sorted(dic) has all the keys of dic in sorted order.It only has the keys and not keyvalue pairs. sorted(dic) will have [1,2,3,5,8]

  • For each key in sorted order, add the key and the corresponding value into dic2.

  • dic2 has all the key-value pairs in sorted order of keys

Method 2 − Sort dictionary by values

In this approach, the dictionary is sorted in ascending order of values.

Input:

{2:90, 1: 100, 8: 3, 5: 67, 3: 5}

Output:

{8:3, 3:5 ,5:67 , 2:90, 1:100}

As shown above, we can see the dictionary is sorted according to its values.

  • We use the sorted() and items() methods together to sort the dictionary by value.

  • The items() is used to retrieve the items or values of the dictionary.

  • The key=lambda x: x[1] is a sorting mechanism that uses a lambda function.

  • This gives us key value pairs ehich are then converted into a dictionary using dict().

Example

 Live Demo

dic={2:90, 1: 100, 8: 3, 5: 67, 3: 5}
dic2=dict(sorted(dic.items(),key= lambda x:x[1]))
print(dic2)

Output

{8: 3, 3: 5, 5: 67, 2: 90, 1: 100}
raja
Published on 11-Mar-2021 09:15:54
Advertisements