HowToDoInJava

  • Python
  • Java
  • Spring Boot
  • Dark Mode
Home / Python / Python OrderedDict – Ordered Dictionary

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?

Let us know if you liked the post. That’s the only way we can improve.
TwitterFacebookLinkedInRedditPocket

About Lokesh Gupta

A family guy with fun loving nature. Love computers, programming and solving everyday problems. Find me on Facebook and Twitter.

Comments are closed on this article!

Search Tutorials

Python Tutorial

  • Python Introduction
  • Python Install in Sublime
  • Python Keywords
  • Python Comments
  • Python Variables
  • Python Data Types
  • Python Type Conversion
  • Python References
  • Python Examples

Python Flow Control

  • Python if…else
  • Python for Loop
  • Python while Loop
  • Python break
  • Python continue
  • Python pass

Python Datatypes

  • Python Integer
  • Python String
  • Python List
  • Python Tuple
  • Python Set
  • Python Dictionary
  • Python OrderedDict
  • Python MultiDict
  • Python Priority Queue

Python Advanced Topics

  • Python Lists vs Tuples
  • Python Comparing Tuples
  • Python Unpacking Tuples
  • Python CSV Files

Python Libraries

  • Python Httplib2

Meta Links

  • About Me
  • Contact Us
  • Privacy policy
  • Advertise
  • Guest and Sponsored Posts

Recommended Reading

  • 10 Life Lessons
  • Secure Hash Algorithms
  • How Web Servers work?
  • How Java I/O Works Internally?
  • Best Way to Learn Java
  • Java Best Practices Guide
  • Microservices Tutorial
  • REST API Tutorial
  • How to Start New Blog

Copyright © 2020 · HowToDoInjava.com · All Rights Reserved. | Sitemap

  • Sealed Classes and Interfaces