Is it possible to add a new Key/Value to the beginning of the dictionary instead of the back

Viewed 35

if I have a dictionary: d = {1:a}, and I want to add a new key and value to the beginning of the dictionary, instead of adding it to the back, is that possible? For example, it would be like:

dictionary = {1:a}
dictionary[2] = 'b'
print(d)

>>> {2:b, 1:a}
1 Answers

You can make the dictionary a collections.OrderedDict object instead and use its move_to_end method to move the new key to the beginning of the dict with the last=False argument:

from collections import OrderedDict

dictionary = OrderedDict({1: 'a'})
dictionary[2] = 'b'
dictionary.move_to_end(2, last=False)
print(dict(dictionary))

This outputs:

{2: 'b', 1: 'a'}
Related