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()
Python3
from collections import OrderedDict
iniordered_dict = OrderedDict([('akshat', '1'), ('nikhil', '2')])
iniordered_dict.update({'manjeet': '3'})
iniordered_dict.move_to_end('manjeet', last=False)
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
Python3
from collections import OrderedDict
ini_dict1 = OrderedDict([('akshat', '1'), ('nikhil', '2')])
ini_dict2 = OrderedDict([("manjeet", '4'), ("akash", '4')])
both = OrderedDict(list(ini_dict2.items()) + list(ini_dict1.items()))
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.
Python3
from collections import OrderedDict
ini_dict = OrderedDict([('akshat', '1'), ('nikhil', '2')])
iniordered_dict = OrderedDict()
iniordered_dict.update({'manjeet':'3'})
iniordered_dict.move_to_end('manjeet', last = False)
while ini_dict:
iniordered_dict.update({ini_dict.popitem(last=False)})
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.
Don't miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills, become a part of the hottest trend in the 21st century.Dive into the future of technology - explore the
Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.
Commit to GfG's Three-90 Challenge! Purchase a course, complete 90% in 90 days, and save 90% cost click here to explore.
Last Updated :
15 May, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...