Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Defaultdict in Python
Next article icon

OrderedDict in Python

Last Updated : 02 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

An OrderedDict is a dictionary subclass that remembers the order in which keys were first inserted. The only difference between dict() and OrderedDict() lies in their handling of key order in Python.

OrderedDict vs dict in Python

Note: Starting from Python 3.7, regular dictionaries (dict) also maintain insertion order. In Python 3.6, this was just an implementation detail, but in Python 3.7+, it became an official language feature. This means OrderedDict is only necessary if you’re working with older Python versions or need extra features like reordering items.

OrderedDict maintains the sequence in which keys are added, ensuring that the order is preserved during iteration. In contrast, a standard dictionary does not guarantee any specific order when iterated, providing values in an arbitrary sequence. OrderedDict distinguishes itself by retaining the original insertion order of items.

Example: In this example, the below code demonstrates the difference between a regular dictionary (`dict`) and an ordered dictionary (`OrderedDict`). It first prints the items in a regular dictionary (`d`) where the order of insertion is not guaranteed.

Python
from collections import OrderedDict  print("dict") d = {} d['a'] = 1 d['b'] = 2 d['c'] = 3 d['d'] = 4  for key, value in d.items():     print(key, value)  print("ordered dict") od = OrderedDict() od['d'] = 4 od['b'] = 2 od['a'] = 1 od['c'] = 3  for key, value in od.items():     print(key, value) 

Output
dict a 1 b 2 c 3 d 4 ordered dict d 4 b 2 a 1 c 3 

Python Dictionary Ordered

There are various important points related to python dictionary ordering here , we are discussing some important points related to Python dictionary ordering those are following.

  1. Key value Change
  2. Deletion and Re-Inserting
  3. Equality Comparison
  4. OrderedDict Reversal
  5. OrderedDict Popitem Last
  6. Key Insertion at Arbitrary Position
  7. Collections Module

Key value Change in Python Dictionary Order

If the value of a certain key is changed, the position of the key remains unchanged in OrderedDict. this Python method demonstrates changing the value associated with a key in an OrderedDict.

Example : In this example the below Python code uses an OrderedDict to demonstrate changing the value associated with a specific key. Initially, it creates an OrderedDict with keys ‘a’ through ‘d’ and respective values 1 through 4.

Python
from collections import OrderedDict  print("before") od = OrderedDict() od['a'] = 1 od['b'] = 2 od['c'] = 3 od['d'] = 4 for key, value in od.items():     print(key, value)  print("after") od['c'] = 5 for key, value in od.items():     print(key, value) 

Output
before a 1 b 2 c 3 d 4 after a 1 b 2 c 5 d 4 

Equality Comparison in Python Dictionary Order

OrderedDicts in Python can be compared for equality not only based on their content but also considering the order of insertion. This is useful when comparing two OrderedDicts for both key-value pairs and their order.

Example : In this example the code creates two OrderedDicts, `od1` and `od2`, with different orderings of key-value pairs. It then demonstrates that the order of insertion is considered when comparing them for equality using the `==` operator, resulting in `False`.

Python
from collections import OrderedDict  # Create two ordered dictionaries with different orderings od1 = OrderedDict([('a', 1), ('b', 2), ('c', 3)]) od2 = OrderedDict([('c', 3), ('b', 2), ('a', 1)])  # Compare the ordered dictionaries for equality print(od1 == od2)   

Output
False 

OrderedDict Reversal in Python Dictionary Order

After initializing an `OrderedDict` named `my_dict` with specific key-value pairs, the code attempts to reverse the order of these pairs using the reverse() method. However, `OrderedDict` does not natively support a `reverse()` method. To reverse the order, the code correctly employs Python’s reversed() function combined with list() and items() to obtain a reversed list of key-value pairs. This reversed list is then used to construct a new `OrderedDict` named `reversed_dict`, demonstrating the ability to reverse the order of elements in an `OrderedDict` while preserving the original key-value associations

Example : In this example the below code Creates an OrderedDict named my_dict with elements in a specific order and uses reversed() along with list() and items() to reverse the list of key-value pairs from my_dict. Then, OrderedDict() reconstructs the dictionary in reversed order and prints each key-value pair in reversed order.

Python
from collections import OrderedDict  d1 = OrderedDict([('a', 1), ('b', 2), ('c', 3)])  # Reverse the OrderedDict using reversed() d2 = OrderedDict(reversed(list(d1.items())))  # reversed dictionary for key, value in d2.items():     print(key, value) 

Output
c 3 b 2 a 1 

OrderedDict Popitem() in Python Dictionary Order

The popitem() method in OrderedDict can be used with the last parameter to remove and return the last inserted key-value pair. This is useful when you want to process items in a last-in, first-out manner. Using `popitem(last=True)` on an OrderedDict would remove and return the most recently added item, providing flexibility in managing the order of elements.

Example : In this example the below code uses an OrderedDict and applies the `popitem` method with `last=True` to remove and store the last inserted key-value pair. It then prints the removed item, resulting in the output: `(‘c’, 3)`.

Python
from collections import OrderedDict  d = OrderedDict([('a', 1), ('b', 2), ('c', 3)]) last_item = d.popitem(last=True)  print(last_item)   

Output
('c', 3) 

Key Insertion at Arbitrary Position in Python Dictionary Ordered

OrderedDict allows inserting a new key at a specific position using the move_to_end method. This flexibility allows dynamic reordering of keys based on usage or priority.

Example : In this example the below Python code uses an OrderedDict to create a dictionary with ordered key-value pairs. It then employs the `move_to_end` method to reposition key ‘a’ to the end and key ‘b’ to the beginning.

Python
from collections import OrderedDict  d = OrderedDict([('a', 1), ('b', 2), ('c', 3)])  # Move key 'a' to the end d.move_to_end('a')  # Move key 'b' to the beginning d.move_to_end('b', last=False)  for key, value in d.items():     print(key, value) 

Output
b 2 c 3 a 1 

Deletion and Re-Inserting in Python Dictionary Ordered

Deleting and re-inserting the same key will push it to the back as OrderedDict, however, maintains the order of insertion. This method showcases deletion and re-insertion operations in a Python OrderedDict. Initially, it populates the OrderedDict with key-value pairs, deletes an entry, prints the updated OrderedDict, and subsequently re-inserts the deleted entry, demonstrating the ordered nature of the dictionary.

Example :In this example the below python code demonstrates deletion, re-insertion, and printing of items in an OrderedDict. It first prints the OrderedDict items, then deletes the entry with key ‘c’, prints the updated OrderedDict, and finally re-inserts ‘c’ with its value, printing the OrderedDict again.

Python
from collections import OrderedDict  print("Before deleting:\n") od = OrderedDict() od['a'] = 1 od['b'] = 2 od['c'] = 3 od['d'] = 4  for key, value in od.items():     print(key, value)  print("\nAfter deleting:\n") od.pop('c') for key, value in od.items():     print(key, value)  print("\nAfter re-inserting:\n") od['c'] = 3 for key, value in od.items():     print(key, value) 

Output
Before deleting:  a 1 b 2 c 3 d 4  After deleting:  a 1 b 2 d 4  After re-inserting:  a 1 b 2 d 4 c 3 

Collections Module in Python Dictionary Order

OrderedDict is part of the collections module in Python. It provides all the methods and functionality of a regular dictionary, as well as some additional methods that take advantage of the ordering of the items. Here are some examples of using OrderedDict in Python:

Example :In this example the below code uses an OrderedDict to create a dictionary with ordered key-value pairs. It adds a new item ‘d’ to the end and inserts items ‘e’ and ‘f’ at the beginning, with ‘e’ being moved to the front. The final loop prints the dictionary items in the order they were added.

Python
from collections import OrderedDict  # Create an ordered dictionary of key-value pairs d = OrderedDict([('a', 1), ('b', 2), ('c', 3)])  # Add a new item to the end of the dictionary d['d'] = 4  # Add a new item at a specific position in the dictionary # my_dict.update({'e': 5, 'f': 6}) or below d.update([('e', 5), ('f', 6)]) d.move_to_end('e', last=False)  # Iterate over the dictionary in the order in which items were added for key, value in d.items():     print(key, value) 

Output
e 5 a 1 b 2 c 3 d 4 f 6 

Time Complexity:

  • Get item(Key): O(1)
  • Set item(key, value): O(1)
  • Delete item(key): O(n)
  • Iteration: O(n)

Space Complexity: O(n)

OrderedDict is a dictionary subclass in Python that remembers the order in which items were added. In a regular Python dictionary, the order of the items is not guaranteed, and it may change between different runs of the program or different versions of Python. However, an OrderedDict preserves the order of the items as they were added, even if new items are later added or existing items are changed.

Other Considerations

  • Ordered dict in Python version 2.7 consumes more memory than normal dict. This is due to the underlying Doubly Linked List implementation for keeping the order. In Python 2.7 Ordered Dict is not dict subclass, it’s a specialized container from collections module.
  • Starting from Python 3.7, insertion order of Python dictionaries is guaranteed.
  • Ordered Dict can be used as a stack with the help of popitem function. Try implementing LRU cache with Ordered Dict.


Next Article
Defaultdict in Python

S

Sri Sanketh Uppalapati
Improve
Article Tags :
  • Python
  • Python collections-module
Practice Tags :
  • python

Similar Reads

  • Python Collections Module
    The collection Module in Python provides different types of containers. A Container is an object that is used to store different objects and provide a way to access the contained objects and iterate over them. Some of the built-in containers are Tuple, List, Dictionary, etc. In this article, we will
    13 min read
  • Namedtuple in Python
    Python supports a type of container dictionary called "namedtuple()" present in the module "collections". In this article, we are going to see how to Create a NameTuple and operations on NamedTuple. What is NamedTuple in Python?In Python, NamedTuple is present inside the collections module. It provi
    8 min read
  • Deque in Python
    A deque stands for Double-Ended Queue. It is a data structure that allows adding and removing elements from both ends efficiently. Unlike regular queues, which are typically operated on using FIFO (First In, First Out) principles, a deque supports both FIFO and LIFO (Last In, First Out) operations.
    6 min read
  • ChainMap in Python
    Python contains a container called "ChainMap" which encapsulates many dictionaries into one unit. ChainMap is member of module "collections". Example: # Python program to demonstrate # ChainMap from collections import ChainMap d1 = {'a': 1, 'b': 2} d2 = {'c': 3, 'd': 4} d3 = {'e': 5, 'f': 6} # Defin
    3 min read
  • Python | Counter Objects | elements()
    Counter class is a special type of object data-set provided with the collections module in Python3. Collections module provides the user with specialized container datatypes, thus, providing an alternative to Python's general-purpose built-ins like dictionaries, lists, and tuples. Counter is a sub-c
    6 min read
  • OrderedDict in Python
    An OrderedDict is a dictionary subclass that remembers the order in which keys were first inserted. The only difference between dict() and OrderedDict() lies in their handling of key order in Python. OrderedDict vs dict in PythonNote: Starting from Python 3.7, regular dictionaries (dict) also mainta
    10 min read
  • Defaultdict in Python
    In Python, defaultdict is a subclass of the built-in dict class from the collections module. It is used to provide a default value for a nonexistent key in the dictionary, eliminating the need for checking if the key exists before using it. Key Features of defaultdict:When we access a key that doesn
    6 min read
  • Collections.UserDict in Python
    An unordered collection of data values that are used to store data values like a map is known as Dictionary in Python. Unlike other Data Types that hold only a single value as an element, Dictionary holds key:value pair. Key-value is provided in the dictionary to make it more optimized. Note: For mo
    2 min read
  • Collections.UserList in Python
    Python Lists are array-like data structure but unlike it can be homogeneous. A single list may contain DataTypes like Integers, Strings, as well as Objects. List in Python are ordered and have a definite count. The elements in a list are indexed according to a definite sequence and the indexing of a
    2 min read
  • Collections.UserString in Python
    Strings are the arrays of bytes representing Unicode characters. However, Python does not support the character data type. A character is a string of length one. Example: C/C++ Code # Python program to demonstrate # string # Creating a String # with single Quotes String1 = 'Welcome to the Geeks Worl
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences