Loading video player…

Using OrderedDict in Python (Overview)

Sometimes you need a Python dictionary that remembers the order of its items. In the past, you had only one tool for solving this specific problem: Python’s OrderedDict. It’s a dictionary subclass specially designed to remember the order of items, which is defined by the insertion order of keys.

This changed in Python 3.6. The built-in dict class now keeps its items ordered as well. Because of that, many in the Python community now wonder if OrderedDict is still useful. A closer look at OrderedDict will uncover that this class still provides valuable features.

In this video course, you’ll learn how to:

  • Create and use OrderedDict objects in your code
  • Identify the differences between OrderedDict and dict
  • Understand the pros and cons of using OrderedDict vs dict

With this knowledge, you’ll able to choose the dictionary class that best fits your needs when you want to preserve the order of items.

By the end of the course, you’ll see an example of implementing a dictionary-based queue using OrderedDict, which would be more challenging if you used a regular dict object.

Note that this course uses bpython, but you can also use the standard Python REPL.

Download

Sample Code (ZIP)

938 bytes
Download

Course Slides (PDF)

5.5 MB

00:00 Using OrderedDict in Python.

00:04 Sometimes you need a Python dictionary that remembers the order of its items. In the past, you only had one tool for solving this specific problem: Python’s OrderedDict. It’s a dictionary subclass specifically designed to remember the order of items, which is defined by the insertion order of keys, but this changed in Python 3.6.

00:24 The built-in dict class now keeps its items ordered as well. Because of that, many in the Python community now wonder if OrderedDict is still useful.

00:32 A closer look at the class will uncover that it still provides valuable features. In this course, you’ll learn how to create and used OrderedDict objects in your code,

00:45 identify the differences between OrderedDict and dict, and understand the pros and cons of using OrderedDict vs dict.

00:52 With this knowledge, you’ll be able to choose the dictionary class that best fits your needs when you want to preserve the order of items. By the end of the course, you’ll see an example of implementing a dictionary-based queue using OrderedDict, which would be more challenging if you used a regular dictionary.

01:09 Any code that you see running in the REPL will be using the bpython interpreter. This is a replacement Python interpreter that offers a number of enhancements, including code highlighting and suggestions.

01:19 But any code you see running on-screen will work in the Python REPL, which is typically accessed by typing python or python3 at your terminal or command-line prompt. So now you know what’s going to be covered, let’s get started.

Become a Member to join the conversation.