Open In App

Python – Insertion at the beginning in OrderedDict

Last Updated : 15 May, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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




# 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 

Python3




# 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.

Python3




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.



Previous Article
Next Article

Similar Reads

Python | Check order of character in string using OrderedDict( )
Given an input string and a pattern, check if characters in the input string follows the same order as determined by characters present in the pattern. Assume there won’t be any duplicate characters in the pattern. Examples: Input: string = "engineers rock"pattern = "er";Output: trueExplanation: All 'e' in the input string are before all 'r'.Input:
3 min read
LRU Cache in Python using OrderedDict
LRU (Least Recently Used) Cache discards the least recently used items first. This algorithm requires keeping track of what was used when, which is expensive if one wants to make sure the algorithm always discards the least recently used item. General implementations of this technique require keeping "age bits" for cache-lines and track the "Least
4 min read
How to iterate over OrderedDict in Python?
An OrderedDict is a subclass that preserves the order in which the keys are inserted. The difference between OrderedDict and Dict is that the normal Dict does not keep a track of the way the elements are inserted whereas the OrderedDict remembers the order in which the elements are inserted. Explanation: Input : original_dict = { 'a':1, 'b':2, 'c':
2 min read
K’th Non-repeating Character in Python using List Comprehension and OrderedDict
Given a string and a number k, find the k-th non-repeating character in the string. Consider a large input string with lacs of characters and a small character set. How to find the character by only doing only one traversal of input string? Examples: Input : str = geeksforgeeks, k = 3 Output : r First non-repeating character is f, second is o and t
2 min read
OrderedDict in Python
An OrderedDict is a dictionary subclass that remembers the order in which keys were first inserted. The only difference between dict() and OrderedDict() lies in their handling of key order in Python. OrderedDict vs dict in Python`OrderedDict` maintains the sequence in which keys are added, ensuring that the order is preserved during iteration. In c
8 min read
How to convert JSON to Ordereddict?
The full-form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called json. To use this feature, we import the json package in Python script. The text in JSON is done through quoted-
2 min read
How to convert a nested OrderedDict to dict?
In this article, we will discuss how to convert a nested OrderedDict to dict? Before this we must go through some concepts: Dictionary in Python is an unordered collection of data values, used to store data values like a map, which, unlike other Data Types that hold only a single value as an element, Dictionary holds the key:value pair. Key-value i
3 min read
How to convert Ordereddict to JSON?
In this article, we will learn How to convert a nested OrderedDict to JSON? Before this we must go through some concepts: The full-form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in packa
3 min read
Python | Insert the string at the beginning of all items in a list
Given a list, write a Python program to insert some string at the beginning of all items in that list. Examples: Input : list = [1, 2, 3, 4], str = 'Geek' Output : list = ['Geek1', 'Geek2', 'Geek3', 'Geek4']Input : list = ['A', 'B', 'C'], str = 'Team' Output : list = ['TeamA', 'TeamB', 'TeamC'] There are multiple ways to insert the string at the be
3 min read
Python | Add list at beginning of list
Sometimes, while working with Python list, we have a problem in which we need to add a complete list to another. The rear end addition to list has been discussed before. But sometimes, we need to perform an append at beginning of list. Let's discuss certain ways in which this task can be performed. Method #1 : Using "+" operator The "+" operator ca
5 min read
Practice Tags :