Python - Insertion at the beginning in OrderedDict
Given an ordered dict, write a program to insert items in the beginning of the ordered dict.
Examples:
Input: original_dict = {'a':1, 'b':2} item to be inserted ('c', 3) Output: {'c':3, 'a':1, 'b':2}
Input: original_dict = {'akshat':1, 'manjeet':2} item to be inserted ('nikhil', 3) Output: {'nikhil':3, 'akshat':1, 'manjeet':2}
Below are various methods to insert items in starting of ordered dict.
Method #1: Using OrderedDict.move_to_end()
# Python code to demonstrate
# insertion of items in beginning of ordered dict
from collections import OrderedDict
# Initialising ordered_dict
iniordered_dict = OrderedDict([('akshat', '1'), ('nikhil', '2')])
# Inserting items in starting of dict
iniordered_dict.update({'manjeet': '3'})
iniordered_dict.move_to_end('manjeet', last=False)
# Printing result
print("Resultant Dictionary : "+str(iniordered_dict))
Output
Resultant Dictionary : OrderedDict([('manjeet', '3'), ('akshat', '1'), ('nikhil', '2')])
Time complexity: O(n), where n is the number of values in the dictionary.
Auxiliary Space: O(1), constant extra space is required
Method #2: Using Naive Approach
This method only works in case of unique keys
# Python code to demonstrate
# insertion of items in beginning of ordered dict
from collections import OrderedDict
# initialising ordered_dict
ini_dict1 = OrderedDict([('akshat', '1'), ('nikhil', '2')])
ini_dict2 = OrderedDict([("manjeet", '4'), ("akash", '4')])
# adding in beginning of dict
both = OrderedDict(list(ini_dict2.items()) + list(ini_dict1.items()))
# print result
print ("Resultant Dictionary :"+str(both))
Output
Resultant Dictionary :OrderedDict([('manjeet', '4'), ('akash', '4'), ('akshat', '1'), ('nikhil', '2')])
Method #3: Using OrderedDict.popitem()
To add a new key-value pair at the beginning of an OrderedDict, we can use popitem() method with a new OrderedDict. This method returns and removes the last key-value pair in the OrderedDict. We can keep popping the last key-value pair and adding it to a new OrderedDict until we get the desired order of insertion.
from collections import OrderedDict
# Initialising ordered_dict
ini_dict = OrderedDict([('akshat', '1'), ('nikhil', '2')])
# Creating a iniordered ordered dict
iniordered_dict = OrderedDict()
# Inserting new key-value pair at the beginning of iniordered_dict
iniordered_dict.update({'manjeet':'3'})
iniordered_dict.move_to_end('manjeet', last = False)
# popitem() method to remove and insert key-value pair at beginning
while ini_dict:
iniordered_dict.update({ini_dict.popitem(last=False)})
# Print result
print("Resultant Dictionary :" + str(iniordered_dict))
Output
Resultant Dictionary :OrderedDict([('manjeet', '3'), ('akshat', '1'), ('nikhil', '2')])
Time Complexity: O(n), where N is the number of key-value pairs in the ini_dict
Auxiliary Space: O(n), because we are iterating through all the key-value pairs in ini_dict once.