Write a python program to insertion at the beginning in ordereddict?

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    Given an ordered dict, write a program to insert items in beginning of 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’)]) 
     

      
    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’)]) 
     


    In this tutorial, we will learn how to write a program that will insert at the beginning in an OrderedDict using Python. For a given dictionary that is an OrderedDict, we have to insert items at the beginning of the dictionary.

    In an OrderedDict the order of the insertion of keys is maintained, unlike in a normal dictionary where the order of the keys is not saved.

    Let us look at the sample input and output of the program.

    Input: original_dict = {1: 'a', 2: 'b', 3:'c'} item to be inserted (4, 'd')

    Output: {4: 'd', 1: 'a', 2: 'b', 3: 'c'}

    To execute this task we can use the following approaches:

    1. Using concatenation operator (+)
    2. Using move_to_end() method

    Approach 1: Using concatenation operator (+)

    The concatenation operator (+) works for joining strings and lists in Python. We can convert the values in the dictionary in the list format and then using this operator, we can join the item which has to be inserted, and the given dictionary in a new dictionary, so that the item will be added in the beginning.

    Algorithm

    Follow the algorithm to understand the approach better.

    Step 1- Import OrderedDict from collections

    Step 2- Initialise dictionary with items

    Step 3- Initialise item which has to be inserted

    Step 4- Declare a dictionary that will store the result

    Step 5- Use (+) to add the item at the beginning of the dictionary

    Step 6- Print the new dictionary as the result

    Python Program 1

    Look at the program to understand the implementation of the above-mentioned approach. To get the key-value pairs from the dictionary, we have used the items() method which will return all the items present in a dictionary. We have used the list() method to convert the items of the dictionary in list format.

    from collections import OrderedDict
    dic1 = OrderedDict([('A', '100'), ('B', '200'), ('C', '300')])
    insrt = OrderedDict([("D", '400')])
      
    final = OrderedDict(list(insrt.items()) + list(dic1.items()))
      
    # print result
    print ("Resultant Dictionary :")
    print(final)


    Resultant Dictionary :
    OrderedDict([('D', '400'), ('A', '100'), ('B', '200'), ('C', '300')])

    Approach 2: Using move_to_end() method

    The move_to_end() is a method of the OrderedDict subclass. This method can be used to move an existing key to either end of the dictionary. To add the new item in the dictionary, we can use the update() method. This method will add the specified item at the end of the list.

    Algorithm

    Follow the algorithm to understand the approach better.

    Step 1- Import OrderedDict in the program

    Step 2- Initialise a dictionary with items

    Step 3- Use update() to add the new item in the dictionary

    Step 4- Use move_to_end() to move the inserted item at the beginning

    Step 5- Print the new dictionary as the result

    Python Program 2

    Look at the program to understand the implementation of the above-mentioned approach. The item which has to be inserted at the beginning is first added in the dictionary using update() then it is shifted to the beginning using the move_to_end() where the position is given as last=False.

    from collections import OrderedDict  
    dic1 = OrderedDict([('A', '100'), ('B', '200'), ('C', '300')])
    
    dic1.update({"D": '400'})
    print(dic1)
    
    dic1.move_to_end("D", last=False)
      
    
    print ("Resultant Dictionary :")
    print(dic1)
    


    OrderedDict([('A', '100'), ('B', '200'), ('C', '300'), ('D', '400')])
    Resultant Dictionary :
    OrderedDict([('D', '400'), ('A', '100'), ('B', '200'), ('C', '300')])

    Conclusion

    In this tutorial, we have seen two different approaches for inserting an item at the beginning of an OrderedDict. We have also seen what an OrderedDict is and how we can use different built-in methods to execute the task.

    What is an OrderedDict in Python?

    Python's OrderedDict is a dict subclass that preserves the order in which key-value pairs, commonly known as items, are inserted into the dictionary. When you iterate over an OrderedDict object, items are traversed in the original order. If you update the value of an existing key, then the order remains unchanged.

    How do I create an OrderedDict?

    OrderedDict is part of python collections module. We can create an empty OrderedDict and add items to it. If we create an OrderedDict by passing a dict argument, then the ordering may be lost because dict doesn't maintain the insertion order. If an item is overwritten in the OrderedDict, it's position is maintained.

    How is an OrderedDict implemented in Python?

    Under the hood, OrderedDict is implemented with the help of the doubly-linked list data structure. This is so that the order of the OrderedDict is retained.

    How do you create an empty OrderedDict in Python?

    “generate an empty ordereddict in python” Code Answer.
    from collections import OrderedDict..
    d = OrderedDict().
    d['a'] = 1..
    d['b'] = 2..
    d['c'] = 3..
    for key, value in d. items():.