Sort Python Dictionaries by Key or Value

PythonServer Side ProgrammingProgramming

When it is required to sort the dictionaries in Python using a key or a value, a dictionary can be defined, and key value pairs can be inserted into it. A ‘for’ loop can be used to iterate through the key value pair, and sort it using ‘sort’ method. This method can be called.

Below is the demonstration of the same −

Example

def my_dict():

my_key_value_pair ={}

my_key_value_pair[2] = 56
my_key_value_pair[1] = 2
my_key_value_pair[5] = 12
my_key_value_pair[4] = 24
my_key_value_pair[6] = 18
my_key_value_pair[3] = 323

print ("The keys and values after sorting in alphabetical order based on the key are : ")

for i in sorted (my_key_value_pair) :
   print((i, my_key_value_pair[i]))

my_dict()

Output

The keys and values after sorting in alphabetical order based on the key are :
(1, 2)
(2, 56)
(3, 323)
(4, 24)
(5, 12)
(6, 18)

Explanation

  • A method is defined, that initially assigns an empty dictionary to a variable.

  • The index of the empty dictionary is accessed and elements are assigned to indices.

  • The ‘sorted’ method is used to iterate through the dictionary, and display it on the console.

  • This method is called.

  • The output is displayed on the console.

raja
Published on 17-Apr-2021 12:15:38
Advertisements