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:
Python - Filter dictionary values in heterogeneous dictionary
Next article icon

Regular Dictionary vs Ordered Dictionary in Python

Last Updated : 05 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Dictionary in Python is an unordered collection of data values, used to store data values like a map, unlike other Data Types that hold only a single value as an element, a Dictionary holds key: value pair. Key-value is provided in the dictionary to make it more optimized. A regular dictionary type does not track the insertion order of the (key, value) pairs and thus iterates through the keys based on how they are stored in the hash table which in turn is based on random values to reduce collisions .In contrast to this Python provides the OrderedDict type which remembers the insertion order of (key, value) pairs in the dictionary and thus preserves the order. OrderedDict consumes more memory than a regular dictionary in Python because of the underlying Doubly LinkedList implementation to preserve the order.

Note : A regular dictionary maintains the insertion order from Python 3.7 onwards.

Regular Dictionary vs Ordered Dictionary in Python

There are differences between a Regular Dictionary and an Ordered Dictionary in Python, here we are discussing differences between some characteristics of a Regular Dictionary and vs Ordered Dictionary.

  • Create and Print Dictionary
  • Dictionary Deletion and Re-insertion
  • Ordering of Elements
  • Equality Comparison

Create and Print Dictionary

In a regular dictionary, the order of key-value pairs is not guaranteed, so the output may vary when printing. In contrast, an ordered dictionary maintains the order of insertion, ensuring that elements are printed in the sequence they were added

In this example, code illustrates the distinction between a regular dictionary and an ordered dictionary in Python. It creates a regular dictionary with arbitrary order and prints its content, then generates an ordered dictionary using `collections.OrderedDict()`.

Python
import collections  # Creating a regular dictionary print('Regular dictionary:') d = {chr(k): k for k in range(ord('a'), ord('g'))}  for k, v in d.items():     print(k, v)  # Creating an Ordered dictionary print('\nOrderedDict:') d = collections.OrderedDict() [d.setdefault(chr(k), k) for k in range(ord('a'), ord('g'))]  for k, v in d.items():     print(k, v) 

Output (Python 3.6 and earlier)::

Regular dictionary:
('a', 97)
('c', 99)
('b', 98)
('e', 101)
('d', 100)
('f', 102)
OrderedDict:
('a', 97)
('b', 98)
('c', 99)
('d', 100)
('e', 101)
('f', 102)

Time complexity : O(N)
Space Complexity : O(N)

Note: Starting from Python 3.7, insertion order of Python dictionaries is guaranteed.

Dictionary Deletion and Re-insertion

Deleting and re-inserting the same key will push it to the back as OrderedDict however maintains the order of insertion. In a regular dictionary, deletion and re-insertion of a key-value pair do not guarantee a specific order upon iteration. However, in an ordered dictionary, the order of insertion is preserved, so deleting and re-inserting a key-value pair maintains its position in the iteration sequence

In this example Python code demonstrates the use of deletion and re-insertion operations in both a regular dictionary (dict) and an ordered dictionary (OrderedDict).

Python
from collections import OrderedDict     print("Before deleting:\n")   d = {} print("Regular dictionary:") d['a'] = 1 d['b'] = 2 d['c'] = 3 d['d'] = 4 for key, value in d.items():      print(key, value)      od = OrderedDict()  print("\nOrdered dictionary:") 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")   print("Regular dictionary:") d.pop('c') for key, value in d.items():      print(key, value)       print("\nOrdered dictionary:") od.pop('c') for key, value in od.items():      print(key, value)      print("\nAfter re-inserting:\n")   print("Regular dictionary:") d['c'] = 3 for key, value in d.items():      print(key, value)      print("\nOrdered dictionary:") od['c'] = 3 for key, value in od.items():      print(key, value)  

Output (Python 3.6 and earlier):

Before deleting:
Regular dictionary:
('a', 1)
('c', 3)
('b', 2)
('d', 4)
Ordered dictionary:
('a', 1)
('b', 2)
('c', 3)
('d', 4)
After deleting:
Regular dictionary:
('a', 1)
('b', 2)
('d', 4)
Ordered dictionary:
('a', 1)
('b', 2)
('d', 4)
After re-inserting:
Regular dictionary:
('a', 1)
('c', 3)
('b', 2)
('d', 4)
Ordered dictionary:
('a', 1)
('b', 2)
('d', 4)
('c', 3)

Time Complexity : O(n)
Space Complexity :O(1)

Ordering of Elements

In a regular dictionary, the order of elements is not guaranteed, and iterating over its items may not reflect the order of insertion. Conversely, an ordered dictionary, specifically OrderedDict in Python, ensures that the order of elements remains consistent with the sequence of their insertion, providing a reliable and predictable iteration order

In this example code first demonstrates a regular dictionary’s unpredictable order when iterated, printing key-value pairs. Then, it contrasts this with an ordered dictionary, showcasing its guaranteed order of insertion by printing its key-value pairs in the order they were added.

Python
print("Regular Dictionary is :") regular_dict = {'one': 1, 'three': 3, 'two': 2} for key, value in regular_dict.items():     print(key, value)       from collections import OrderedDict print("Ordered Dictionary is :") ordered_dict = OrderedDict([('one', 1), ('three', 3), ('two', 2)]) for key, value in ordered_dict.items():     print(key, value) 

Output :

Regular Dictionary is :
one 1
three 3
two 2
Ordered Dictionary is :
one 1
three 3
two 2

Time Complexity: O(N)
Space Complexity: O(1)

Equality Comparison

Regular dictionaries in Python do not guarantee any specific order of key-value pairs, so their equality comparison checks if the contents are the same, regardless of order. On the other hand, ordered dictionaries preserve the order in which items are inserted, so their equality comparison considers both content and order for equality.

In this example first part uses regular dictionaries (dict1 and dict2) with different key orders, yielding True in the equality check (dict1 == dict2) because regular dictionaries ignore order. The second part involves ordered dictionaries (od1 and od2) with the same content but different key orders, resulting in False in the equality check (od1 == od2) as ordered dictionaries consider both content and order.

Python
print("Regular Dictionary Equality Comparison : ") dict1 = {'one': 1, 'two': 2, 'three': 3} dict2 = {'three': 3, 'two': 2, 'one': 1} print(dict1 == dict2)    from collections import OrderedDict print("Ordered Dictionary Equality Comparison : ") od1 = OrderedDict([('one', 1), ('two', 2), ('three', 3)]) od2 = OrderedDict([('three', 3), ('two', 2), ('one', 1)]) print(od1 == od2)   

Output :

Regular Dictionary Equality Comparison :
True
Ordered Dictionary Equality Comparison :
False


Next Article
Python - Filter dictionary values in heterogeneous dictionary

A

AlapanKar
Improve
Article Tags :
  • Python
  • Python Programs
  • python-dict
Practice Tags :
  • python
  • python-dict

Similar Reads

  • Update Dictionary with other Dictionary - Python
    The task of updating a dictionary with another dictionary involves merging the key-value pairs from one dictionary into another. If a key already exists in the target dictionary, its value is updated with the value from the source dictionary. If the key does not exist in the target dictionary, it is
    4 min read
  • Append Dictionary Keys and Values ( In order ) in Dictionary - Python
    Appending dictionary keys and values in order ensures that the sequence in which they are added is preserved. For example, when working with separate lists of keys and values, we might want to append them in a specific order to build a coherent dictionary. Let's explore several methods to achieve th
    3 min read
  • Reverse Dictionary Keys Order - Python
    We are given a dictionary and our task is to reverse the order of its keys. This means if we have a dictionary like {'a': 1, 'b': 2, 'c': 3} then the output will be {'c': 3, 'b': 2, 'a': 1}. This can be done using methods like reversed(), dictionary comprehensions, or OrderedDict. Let's explore thes
    4 min read
  • Python - Custom order dictionary
    Sometimes, while working with Python dictionaries, we can have a problem in which we need to perform the custom ordering of keys of dictionary. This is quite popular problem, with the advent of newer version of Python, where keys are ordered in Dictionaries, there might be requirement to reorder dic
    3 min read
  • Python - Filter dictionary values in heterogeneous dictionary
    Sometimes, while working with Python dictionaries, we can have a problem in which we need to filter out certain values based on certain conditions on a particular type, e.g all values smaller than K. This task becomes complex when dictionary values can be heterogeneous. This kind of problem can have
    6 min read
  • Sort a Nested Dictionary by Value in Python
    Sorting a nested dictionary in Python involves understanding its structure, defining sorting criteria, and utilizing the `sorted()` function or `.sort()` method with a custom sorting function, often a lambda. This process is essential for organizing complex, hierarchical data efficiently. Mastery of
    3 min read
  • Python | Max/Min of tuple dictionary values
    Sometimes, while working with data, we can have a problem in which we need to find the min/max of tuple elements that are received as values of dictionary. We may have a problem to get index wise min/max. Let's discuss certain ways in which this particular problem can be solved. Method #1 : Using tu
    5 min read
  • Python - Remove duplicate values in dictionary
    Sometimes, while working with Python dictionaries, we can have problem in which we need to perform the removal of all the duplicate values of dictionary, and we are not concerned if any key get removed in the process. This kind of application can occur in school programming and day-day programming.
    8 min read
  • Python - Sorted Nested Keys in Dictionary
    Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract all the keys of nested dictionaries and render them in sorted order. This kind of application can occur in domains in which we work with data. Lets discuss certain ways in which this task can be perf
    4 min read
  • Python - Filter dictionaries with ordered values
    Given the dictionary list, the task is to write a python program to filter dictionaries with values in increasing order i.e sorted. Examples: Input : test_list = [{'gfg' : 2, 'is' : 8, 'good' : 10}, {'gfg' : 1, 'for' : 10, 'geeks' : 9}, {'love' : 3, 'gfg' : 4}] Output : [{'gfg': 2, 'is': 8, 'good':
    4 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