Python OrderedDict

An OrderedDict maintains the insertion order of items added to the dictionary. The order of items is preserved when iterating or serializing also.

from collections import OrderedDict

user = OrderedDict(name='lokesh', id='100', email='admin@gmail.com')

# Iteration
for key in user:
    print(key + ":" + user[key])
    
# Add a Key at the last
user['location'] = 'India'

# Update a Key
user['email'] = 'admin@howtodoinjava.com'

# Delete a Key
del user['email']

# Pop item from last and start
user.popitem()  # from last of dictionary
user.popitem(last=False) # from start of dictionary

# Move item to last and start
user.move_to_end('id')  # move to last
user.move_to_end('id', False)   # move to start

1. Python OrderedDict

In Python, OrderedDict is a dictionary subclass that maintains the order in which keys were first inserted.

Opposite to it, a regular dict doesn’t track the insertion order and iterating it gives the values in an arbitrary order. Note that if we modify an OrderedDict, even then the order of the entries remains the same.

Note that maintaining the order comes with a cost. OrderedDict occupies 50% more memory to store and iterate items due to the extra storage layer required to preserve the ordering of items.

2. Creating OrderedDict

To use the OrderedDict, we need to import it from the collection module.

from collections import OrderedDict

To initialize the OrderedDict, we use its constructor:

user = OrderedDict()

user['name'] = 'lokesh'
user['id'] = 100
user['email'] = 'admin@gmail.com'

print(user)    #OrderedDict([('name', 'lokesh'), ('id', 100), ('email', 'admin@gmail.com')])

We can also use a constructor with arguments to create an OrderedDict.

from collections import OrderedDict

user = OrderedDict(name='lokesh', id=100, email='admin@gmail.com')

print(user)    #OrderedDict([('name', 'lokesh'), ('id', 100), ('email', 'admin@gmail.com')])

Another way to create an OrderedDict is to use its fromKeys() that generates an OrderedDict from a list of keys. It is very handy if we want to create OrderedDict with default values.

keys = ['id', 'name', 'email']

user = OrderedDict.fromkeys(keys, 0) #assigns a default value of 0

3. Iterating through an OrderedDict

The iteration operation is the same as the regular dict datatype. we visit every key and access its value in a for-loop.

from collections import OrderedDict

user = OrderedDict(name='lokesh', id="100", email='admin@gmail.com')

#Iterating using keys

for key in user:
    print(key + ":" + user[key])
    
for key in user.keys():
    print(key + ":" + user[key])
    
#Iterating using items()

for key, value in user.items():
    print(key + ":" + value)  

The program output:

name:lokesh
id:100
email:admin@gmail.com

name:lokesh
id:100
email:admin@gmail.com

name:lokesh
id:100
email:admin@gmail.com

4. Insert, Update and Delete from OrderedDict

We can perform the various data manipulations on OrderedDict as it is a mutable datatype.

Insertion of an item takes place at the end of the dictionary. It is true even if an item is deleted and re-inserted again. Each newly added item always goes to the end.

from collections import OrderedDict

user = OrderedDict(name='lokesh', id=100, email='admin@gmail.com')
user['location'] = 'India'

print(user)    

#OrderedDict([('name', 'lokesh'), ('id', 100), ('email', 'admin@gmail.com'), ('location', 'India')])

Values are always updated in-place. Thus, the position of the key is not affected if the value is updated.

from collections import OrderedDict

user = OrderedDict(name='lokesh', id=100, email='admin@gmail.com')
user['email'] = 'admin@howtodoinjava.com'

print(user) 

#OrderedDict([('name', 'lokesh'), ('id', 100), ('email', 'admin@howtodoinjava.com')])

To delete an item from the OrderedDict, use the del keyword.

from collections import OrderedDict

user = OrderedDict(name='lokesh', id=100, email='admin@gmail.com')
del user['email']

print(user)  

# OrderedDict([('name', 'lokesh'), ('id', 100)])

5. Convert OrderedDict to JSON

The order of items is preserved while serializing to JSON as well. To create the JSON, use the json module as follows:

from collections import OrderedDict
import json

d = OrderedDict()

d['how'] = 1
d['to'] = 2
d['do'] = 3
d['in'] = 4
d['java'] = 5

json.dumps(d)

'{"how": 1, "to": 2, "do": 3, "in": 4, "java": 5}'

6. Difference between dict and OrderedDict

There are few noticeable differences between both datatypes. Let us discuss them.

6.1. move_to_end()

The OrderedDict has a special method move_to_end() that can be used to shift an item at the end or at the start of a dictionary. The start or end is controlled by a parameter last and its default value is True.

  • last=True : moves the item to the last of the dictionary
  • last=False : moves the item to the start of the dictionary
move_to_end(key, last=True)

Let us see an example.

from collections import OrderedDict

user = OrderedDict(name='lokesh', id="100", email='admin@gmail.com')

print(user) #OrderedDict([('name', 'lokesh'), ('id', '100'), ('email', 'admin@gmail.com')])

user.move_to_end('id')

print(user) #OrderedDict([('name', 'lokesh'), ('email', 'admin@gmail.com'), ('id', '100')])

user.move_to_end('id', False)

print(user) #OrderedDict([('id', '100'), ('name', 'lokesh'), ('email', 'admin@gmail.com')])

6.2. popitem()

The regular dict has a method popitem() that removes an item from the rightmost end of the dictionary.

However, OrderedDict allows passing the parameter last, when set to False, the item is removed from the leftmost end of the dictionary.

from collections import OrderedDict

user = OrderedDict(name='lokesh', id="100", email='admin@gmail.com')

print(user.popitem())           #('email', 'admin@gmail.com')
print(user.popitem(last=False)) #('name', 'lokesh')

7. Conclusion

In this Python tutorial, we learned the basics of the OrderedDict datatype. We discussed the differences between a dictionary and OrderedDict. We also learned to create, update and delete the items from the OrderedDict.

Happy Learning !!

Comments

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode