TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Python OrderedDict Tutorial
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python BasicPython Tutorials

Python OrderedDict Tutorial

Last updated: Nov 28, 2023 11:47 pm
By Harsh S.
Share
7 Min Read
Python OrderedDict vs Dict
SHARE

This tutorial explains a special class Python OrderedDict, how it is different from a dict in Python, and provides examples to understand it better.

Contents
OrderedDict in PythonInsertion order in Python 3.7+Sorting a dictionaryComparing methodsChoosing a method

In general, Python dicts are unordered collections of key-value pairs. It means that they are not able to retain the order of their elements. And, while iterating them, the items will not appear in the same sequence. This can be problematic in certain situations where the order of items is important.

For example, if you are creating a log of events, you may want to preserve the order in which events occurred. Or, if you are building a cache, you may want to remove the least recently used items first.

Fortunately, Python provides a few different ways to maintain order in dictionaries.

Python OrderedDict vs Dict

Python dictionaries (or dict objects) are unordered collections of key-value pairs. They don’t preserve the order of their elements when iterating over them.

On the other hand, Python OrderedDict is a subclass of dict that preserves the order in which items are inserted. This can be useful in situations where the order of items is important, such as when creating a log of events or building a cache.

Here is a point-by-point comparison between the two.

Also Read: How to Append Items to a Dict in Python

FeaturePython OrderedDictPython dict
Preserves insertion orderYesNo
PerformanceSlowerFaster
Memory usageHigherLower
AvailabilityPython 3.1 and laterAll versions of Python
Additional methodsSupports methods for managing orderDoes not support methods for managing order
Pros* Guaranteed to maintain order.
* Supports additional methods for managing the order.
* Fast.
* Available in all versions of Python.
Cons* Slower than regular dicts.
* Not available in Python 3.6 and earlier.
* Does not preserve insertion order.
Best use cases* Maintaining a log of events.
* Building a cache.
* Creating a FIFO or LIFO queue.
* Storing data that is naturally ordered, such as dates or times.
* Creating a dictionary of configuration settings.
* Building a simple cache.
Point-by-Point Comparison

OrderedDict in Python

Firstly, the collections.OrderedDict class is a subclass of the dict that preserves the order in which items are inserted. Secondly, when you iterate over OrderedDict, you get the items in their original order.

Python code:

from collections import OrderedDict

events = OrderedDict()

events['start'] = '2023-10-21 18:31 IST'
events['login'] = '2023-10-21 18:32 IST'
events['search'] = '2023-10-21 18:33 IST'

for event, timestamp in events.items():
  print(f"{event}: {timestamp}")

Output:

start: 2023-10-21 18:31 IST
login: 2023-10-21 18:32 IST
search: 2023-10-21 18:33 IST

As you can see, the Python code printed the events in the order they were added to the OrderedDict.

Also Read: How to Merge Dictionaries in Python

Insertion order in Python 3.7+

In Python 3.7 and later, the dictionaries by default maintain the insertion order. This means that you can use a regular dict to retain order, as long as you are using Python 3.7 or later.

Python code:

events = {}

events['start'] = '2023-10-21 18:31 IST'
events['login'] = '2023-10-21 18:32 IST'
events['search'] = '2023-10-21 18:33 IST'

for event, timestamp in events.items():
  print(f"{event}: {timestamp}")

Output:

start: 2023-10-21 18:31 IST
login: 2023-10-21 18:32 IST
search: 2023-10-21 18:33 IST

The events are printed in the order they were added to the dict, following a pattern similar to Python OrderedDict.

Sorting a dictionary

If you need to sort a dictionary by its keys or values, you can use the sorted() function.

Python Code:

events = {
  'start': '2023-10-21 18:31 IST',
  'login': '2023-10-21 18:32 IST',
  'search': '2023-10-21 18:33 IST',
}

sorted_events = sorted(events.items(), key=lambda item: item[0])

for event, timestamp in sorted_events:
  print(f"{event}: {timestamp}")

Output:

login: 2023-10-21 18:32 IST
search: 2023-10-21 18:33 IST
start: 2023-10-21 18:31 IST

It is visible that the events appeared in a sorted manner by their keys.

Comparing methods

MethodDescriptionAdvantagesDisadvantages
Python OrderedDictPreserves insertion order.Sort a dictionary by its keys or values.* Slower than regular dicts.
* Not available in Python 3.6 and earlier.
Insertion order in Python 3.7+Insertion order is guaranteed.* Fast.
* Available in all versions of Python 3.7 and later.
* Not available in Python 3.6 and earlier.
Sorting a dictionarySort a dictionary by its keys or values.* Flexible.
* Can be used to sort dictionaries in any order.
* Does not maintain order after sorting.
Different Methods to Sort a Dictionary

Choosing a method

The best method for maintaining order in dictionaries depends on your specific needs. If you need to guarantee that Python keeps the order, you should use an OrderedDict. In case you are using Python 3.7 or later, you can use a regular dict as long as you are sure that the insertion order will remain intact. If you need to sort a dictionary, you can use the sorted() function.

Here are some specific examples of when you might choose each method:

  • OrderedDict:
    • Maintaining a log of events
    • Building a cache
    • Creating a FIFO or LIFO queue
  • Insertion order in Python 3.7+:
    • The order of an element remains the same when you access it later.
    • Creating a dictionary of configuration settings
    • Building a simple cache
  • Sorting a dictionary:
    • Displaying data in a sorted order
    • Creating a ranked list
    • Grouping data by a particular value

Conclusion – Python OrderedDict vs Dict

In general, Python OrderedDict is the most reliable way to maintain order in dictionaries. However, if you are using Python 3.7 or later, you can use a regular dict as long as you are sure that the insertion order won’t change. If you need to sort a dictionary, you can use the sorted() function.

Lastly, we hope this tutorial contributed to your learning. Please feel free to reach out if you have any questions or need further assistance.

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

Selenium Python Extent Report Guide

10 Python Tricky Coding Exercises

Sign Up For Daily Newsletter

Be keep up! Get the latest breaking news delivered straight to your inbox.
Loading
By signing up, you agree to our Terms of Use and acknowledge the data practices in our Privacy Policy. You may unsubscribe at any time.
Harsh S. Avatar
By Harsh S.
Follow:
Hello, I'm Harsh, I hold a degree in Masters of Computer Applications. I have worked in different IT companies as a development lead on many large-scale projects. My skills include coding in multiple programming languages, application development, unit testing, automation, supporting CI/CD, and doing DevOps. I value Knowledge sharing and want to help others with my tutorials, quizzes, and exercises. I love to read about emerging technologies like AI and Data Science.
Previous Article Create Your Android App in Python Create an Android App in Python
Next Article Python enumerate function Python Enumerate Function

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x