Python OrderedDict – Ordered Dictionary

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

1. Python OrderedDict example

OrderedDict is part of python collections module.

To easily construct OrderedDict, you can use OrderedDict in the collections module.

from collections import OrderedDict

d = OrderedDict()

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

for key in d:
    print(key, d[key])

('how', 1)
('to', 2)
('do', 3)
('in', 4)
('java', 5)

2. Convert OrderedDict to JSON

Order of items is preserved while serializing to JSON as well.

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}'

Happy Learning !!

Was this post helpful?

Join 7000+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.