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).
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:
- update(): adds the new key-value pair.
- move_to_end(last=False): moves the added key to the start of the dictionary.
Using Dictionary Unpacking
This approach creates a new OrderedDict by unpacking the existing one, placing the new key-value pair first.
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:
- {'c': 3, **d}: creates a new dictionary with the new key-value pair at the start.
- Converts it back into an OrderedDict to maintain order explicitly.
Using Concatenation of items() Lists
This method combines two OrderedDict objects by concatenating their items() lists. It’s simple but slightly less efficient.
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:
- list(d2.items()) + list(d1.items()): merges key-value pairs keeping the new one first.
- OrderedDict(...): rebuilds the ordered dictionary from the combined list.
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.
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:
- update() + move_to_end(last=False): adds and positions the new key first.
- popitem(last=False): removes and retrieves items from the original dict in order.
- update(): adds them to the new dictionary sequentially.