Python Insertion at the beginning in OrderedDict (original) (raw)

Last Updated : 10 Nov, 2025

Given an ordered dict, write a program to insert items in the beginning of the ordered dict.

**Example:

**Input: d = {'a':1, 'b':2}
item = ('c', 3)
**Output: {'c':3, 'a':1, 'b':2}

Below are various methods to insert items in starting of ordered dict.

Using move_to_end()

This is the most efficient and recommended method. It inserts the new item and then moves it to the beginning using move_to_end(last=False).

Python `

from collections import OrderedDict d = OrderedDict([('a', 1), ('b', 2)]) d.update({'c': 3}) d.move_to_end('c', last=False) print(d)

`

Output

OrderedDict({'c': 3, 'a': 1, 'b': 2})

**Explanation:

Using Dictionary Unpacking

This approach creates a new OrderedDict by unpacking the existing one, placing the new key-value pair first.

Python `

from collections import OrderedDict

d = OrderedDict([('a', 1), ('b', 2)]) d = OrderedDict({'c': 3, **d}) print(d)

`

Output

OrderedDict({'c': 3, 'a': 1, 'b': 2})

**Explanation:

Using Concatenation of items() Lists

This method combines two OrderedDict objects by concatenating their items() lists. It’s simple but slightly less efficient.

Python `

from collections import OrderedDict

d1 = OrderedDict([('a', 1), ('b', 2)]) d2 = OrderedDict([('c', 3)])

res = OrderedDict(list(d2.items()) + list(d1.items())) print(res)

`

Output

OrderedDict({'c': 3, 'a': 1, 'b': 2})

**Explanation:

Using popitem() Loop

This method repeatedly pops items and rebuilds the dictionary in the desired order. It’s functional but less efficient for large dictionaries.

Python `

from collections import OrderedDict

d = OrderedDict([('a', 1), ('b', 2)]) n1 = OrderedDict()

n1.update({'c': 3}) n1.move_to_end('c', last=False)

while d: n1.update({d.popitem(last=False)}) print(n1)

`

Output

OrderedDict({'c': 3, 'a': 1, 'b': 2})

**Explanation: