Dictionary is a collection in python which is used to store data as Key:value pair.
Example:
dict = { "python" : 1, "C++" : 3, "javaScript" : 2 }
Ordered Dictionary is a special type of dictionary which remembers the order of insertion of keys.
Inserting at the beginning of OrderedDict
We have an OrderedDict in Python and a key-value pair which is entered by the user. We need to add it to the beginning of the OrderedDict.
Input:
orderedDict = {'javascript' : 4, 'python' : 7, 'c' : 4} -> 'r' : 5
Output:
{'r' : 5, 'javascript' : 4, 'python' : 7, 'c' : 4}
Python provides multiple methods to insert an element to the beginning of the OrderedDict.
Method 1:
A simple approach is by creating a new OrderedDict from the entered key value pair and then creating a new one by merging them in such a way that the entered pair comes at the beginning of this OrderedDict.
Program to insert an element at the beginning in OrderedDict
Output:
Method 2: Using Python's built-in method
Python provides a built-in method to add a key-value pair to the orderedDict using update() method and then move the pair to the beginning of the orderedDict using move_to_end() method.
Program to insert an element at the beginning in OrderedDict
Output:
need an explanation for this answer? contact us directly to get an explanation for this answer