Insertion at the beginning in OrderedDict using Python

PythonServer Side ProgrammingProgramming

When it is required to insert the elements at the beginning of an ordered dictionary, the ‘update’ method can be used.

Below is the demonstration of the same −

Example

 Live Demo

from collections import OrderedDict

my_ordered_dict = OrderedDict([('Will', '1'), ('James', '2'), ('Rob', '4')])
print("The dictionary is :")
print(my_ordered_dict)
my_ordered_dict.update({'Mark':'7'})
my_ordered_dict.move_to_end('Mark', last = False)

print("The resultant dictionary is : ")
print(my_ordered_dict)

Output

The dictionary is :
OrderedDict([('Will', '1'), ('James', '2'), ('Rob', '4')])
The resultant dictionary is :
OrderedDict([('Mark', '7'), ('Will', '1'), ('James', '2'), ('Rob', '4')])

Explanation

  • The required packages are imported.

  • An ordered dictionary is created using OrderedDict’.

  • It is displayed on the console.

  • The ‘update’ method is used to specify the key and the value.

  • The ‘move_to_end’ method is used to move a key value pair to the end.

  • The output is displayed on the console.

raja
Published on 17-Apr-2021 12:13:51
Advertisements