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 !!

Comments are closed for this article!

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.