
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Insertion at the Beginning in OrderedDict using Python
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
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.
Advertisements