Python OrderedDict – Reordering, Delete and Reinsert New OrderedDict

Master Python with 70+ Hands-on Projects and Get Job-ready - Learn Python

We’ve been talking about classes from Python collections module- python namedtuple, and python defaultdict. Today, we base our article on Python OrderedDict, another class in ‘collections’.

Here we study what is Python OrderedDict with its syntax and examples. Moreover, we will study comparing to a regular dictionary, and reordering a OrderedDict in Python.

At last, we will cover how to delete and reinsert a key for new ordereddict, and popitem method.

So, let’s start the Python OderedDict Tutorial.

Python OrderedDict - Reordering, Delete and Reinsert New OrderedDict

Python OrderedDict – Reordering, Delete and Reinsert New OrderedDict

What is Python OrderedDict?

Python OrderedDict is just like a regular dictionary in python, but it also saves the order in which pairs were added. Actually, it is a subclass of ‘dict’.

>>> issubclass(OrderedDict,dict)

Output

True

Python OrderedDict Syntax

To define an OrderedDict in python, we import it from the module ‘collections’. Let us see this Python ordereddict example.

>>> from collections import OrderedDict

Then, we call this factory function and assign it to a variable in python.

>>> d=OrderedDict()

We now add some key-value pairs to it.

>>> d['a']=1
>>> d['e']=5
>>> d['d']=4
>>> d['b']=2
>>> d['c']=3

Now, if we access ‘d’, we see that it preserved the order in which we defined the key-value pairs.

>>> d

Output

OrderedDict([(‘a’, 1), (‘e’, 5), (‘d’, 4), (‘b’, 2), (‘c’, 3)])

Comparing to a Regular Dictionary

Let’s try this with a regular dictionary. If we declared this as a regular dictionary, it would produce the pairs according to how the keys are stored in a hash table.

This depends on a random value to reduce collisions.

1. Equality

To a regular dictionary, the order does not matter. Let u take another Python ordereddict example.

>>> {'a': 1, 'e': 5, 'd': 4, 'b': 2, 'c': 3}=={'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}

Output

True

To Python, these two are equal. Let’s create another OrderedDict, and check if it is the same as the OrderedDict ‘d’ we defined above.

>>> e=OrderedDict()
>>> e['a']=1
>>> e['b']=2
>>> e['c']=3
>>> e['d']=4
>>> e['e']=5
>>> e

Output

OrderedDict([(‘a’, 1), (‘b’, 2), (‘c’, 3), (‘d’, 4), (‘e’, 5)])

Now, let’s check if they’re equal.

>>> d==e

Output

False

As you can see, they’re not.

How to Reorder Python OrderedDict?

To reorder a key-value pair to the front or the end of an OrderedDict in python, we have the move_to_end() method. Look, this is ‘d’:

>>> d

Output

OrderedDict([(‘a’, 1), (‘e’, 5), (‘d’, 4), (‘b’, 2), (‘c’, 3)])

Now, let’s move (‘e’,5) to the end.

>>> d.move_to_end('e')
>>> d

Output

OrderedDict([(‘a’, 1), (‘d’, 4), (‘b’, 2), (‘c’, 3), (‘e’, 5)])

This method takes a key as an argument. But it may also take another argument- ‘last’. This may take one of two values: True or False.

When true, the item is moved to the end. And when false, it is moved to the front.

>>> d.move_to_end('a',last=True)
>>> d

Output

OrderedDict([(‘d’, 4), (‘b’, 2), (‘c’, 3), (‘e’, 5), (‘a’, 1)])

Here, we moved (‘a’,1) to the end. Now, let’s move it back to the front.

>>> d.move_to_end('a',last=False)
>>> d

Output

OrderedDict([(‘a’, 1), (‘d’, 4), (‘b’, 2), (‘c’, 3), (‘e’, 5)])

Now, to sort this, we do the following:

>>> d.move_to_end('b')
>>> d

Output

OrderedDict([(‘a’, 1), (‘d’, 4), (‘c’, 3), (‘e’, 5), (‘b’, 2)])

>>> d.move_to_end('c')
>>> d

Output

OrderedDict([(‘a’, 1), (‘d’, 4), (‘e’, 5), (‘b’, 2), (‘c’, 3)])

>>> d.move_to_end('d')
>>> d

Output

OrderedDict([(‘a’, 1), (‘e’, 5), (‘b’, 2), (‘c’, 3), (‘d’, 4)])

>>> d.move_to_end('e')
>>> d

Output

OrderedDict([(‘a’, 1), (‘b’, 2), (‘c’, 3), (‘d’, 4), (‘e’, 5)])

Assigning a Key Again in Python OrderedDict

Let’s define a new OrderedDict in Python for this example.

>>> f=OrderedDict()
>>> f['c']=3
>>> f['e']=5
>>> f['a']=1
>>> f['b']=2
>>> f['d']=4
>>> f

Output

OrderedDict([(‘c’, 3), (‘e’, 5), (‘a’, 1), (‘b’, 2), (‘d’, 4)])

Now, let’s try changing the value of key ‘e’.

>>> f['e']=7
>>> f

Output

OrderedDict([(‘c’, 3), (‘e’, 7), (‘a’, 1), (‘b’, 2), (‘d’, 4)])

Okay. Since the key ‘e’ already exists, the old order is preserved; it isn’t ordered to the end.

Deleting and Reinserting a Key

When we delete a key and then reinsert it, it is ordered to the end of the new order. Let’s try deleting ‘e’.

>>> f.pop('e')

Output

7

>>> f

Output

OrderedDict([(‘c’, 3), (‘a’, 1), (‘b’, 2), (‘d’, 4)])

Now, let’s insert it again.

>>> f['e']=7
>>> f

Output

OrderedDict([(‘c’, 3), (‘a’, 1), (‘b’, 2), (‘d’, 4), (‘e’, 7)])

As you can see, it is at the back of the list now.

Python Popitem ()

The popitem() method in Python may take 0 or 1 argument- ‘last’. When ‘last’ is true, LIFO is followed to delete, otherwise, FIFO is followed. When we don’t pass an argument, last is assumed to be true.

Let’s take a new Python OrderedDict for this.

>>> g=OrderedDict()
>>> g['d']=4
>>> g['b']=2
>>> g['a']=1
>>> g['c']=3
>>> g['e']=5
>>> g

Output

OrderedDict([(‘d’, 4), (‘b’, 2), (‘a’, 1), (‘c’, 3), (‘e’, 5)])

Now, let’s start popping.

>>> g.popitem(last=False)

Output

(‘d’, 4)

>>> g.popitem()

Output

(‘e’, 5)

>>> g.popitem(last=True)

Output

(‘c’, 3)

So, this was all about Python OrderedDict Tutorial. Hope you like our explanation.

Python Interview Questions on Ordereddict

  1. What is an Ordereddict in Python?
  2. Why to use Python Ordereddict?
  3. How is Ordereddict implemented in Python?
  4. How to update Ordereddict in Python?
  5. Give an example of Python Ordereddict.

Conclusion

Hopefully, we’ve covered every important detail about python orderedDict in this article.

We saw how to define them, Syntax, deleting and reinserting, assigning A key to python ordereddict, and we saw methods move_to_end(), popitem(), and pop().

Next, we will discuss Counter python module, yet another class from collections.

If you are Happy with DataFlair, do not forget to make us happy with your positive feedback on Google

courses

DataFlair Team

DataFlair Team creates expert-level guides on programming, Java, Python, C++, DSA, AI, ML, data Science, Android, Flutter, MERN, Web Development, and technology. Our goal is to empower learners with easy-to-understand content. Explore our resources for career growth and practical learning.

2 Responses

  1. Will says:

    I think you are missing a line of code. In section 7, the page reads:

    Now, let’s insert it again.

    >>> f

    should there be a line above this that says something along the lines of “>>> f[‘e’] = 7” ?

Leave a Reply

Your email address will not be published. Required fields are marked *