Unique Features of Python's OrderedDict

Real Python · Intermediate ·⚡ Algorithms & Data Structures ·3y ago

Key Takeaways

The video discusses the unique features of Python's OrderedDict, including its ability to remember the order of items by their insertion order, and how it provides valuable features such as explicit signaling and control over item order. It also covers the OrderedDict's API, which is the same as dict, but enforces key and value order, and how it can be used to create ordered dictionaries with additional features such as moving items to the end and popping items with an equality test.

Full Transcript

using orderdict in Python 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 order dict 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 the built-in dictionary class now keeps these items ordered as well because of that many in the python Community now wonder if order dict is still useful 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 order dict objects in your code identify the differences between order dict and dict and understand the pros and cons of using order dict versus dict 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 orderdict which would be more challenging if you used a regular dictionary any code that you see running in the reple will be using the B python interpreter this is a replacement python interpreter that offers a number of enhancements including code highlighting and suggestions but any code you see running on screen will work in the python reple 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 choosing between order dict and dict fears python dictionaries were unordered data structures python developers were used to this fact and they relied on lists or other sequences when they needed to keep their data in order with time developers found a need for a new type of dictionary one that would keep the items ordered back in 2008 pep 372 introduced the idea of adding a new dictionary class to collections its main goal was to remember the order of items as defined by the order in which the keys were inserted that was the origin of order dict core python developers wanted to fill in the Gap and provide a dictionary that could preserve the order of inserted keys that in turn allowed for a more straightforward implementation of specific algorithms that rely on this property order dict was added to the standard library in Python 3.1 its API is essentially the same as dict however order dictatorates over keys and values in the same order that the keys were inserted if a new entry overwrites an existing entry then the order of items is left unchanged if an entry is deleted and reinserted then it will be moved to the end of the dictionary python 3.6 introduced a new implementation of dictionaries this represents a big win in term of memory usage and iteration efficiency Additionally the new implementation provides a new and somewhat unexpected feature dictionary objects now keep their items in the same order they were introduced initially this feature was considered an implementation detail and a documentation advised against relying on it in Python 3.7 the items ordered feature of dict objects was declared an official part of the Python language specification so from that point on developers could rely on dict if they needed a dictionary that keeps its items ordered at this point a question arises is order dict still needed after this new implementation the answer depends on your specific use case and also how explicit you want to be in your code some features of order dict still make it valuable and different from a regular dict first intense signaling if you use order dict over addict then your code makes it clear that the order of items in the dictionary is important you're clearly communicating that your code needs or relies on the order of items in the underlying dictionary control over the order of items if you need to rearrange or reorder the items in a dictionary then you can use move to end and the enhanced variation of Pop item equality test Behavior if your code Compares dictionaries for equality and the Order of items is important in that comparison then order dict is the right choice there's at least one more reason to continue using Auto addict in your code backwards compatibility relying on regular dictionaries to preserve the order of items will break your code in environments that run versions of python older than 3.6 it's difficult to say if dick will ever fully replace order debt at the moment order debt still offers interesting and valuable features that you might want to consider When selecting a tool for a given job in the next section of the course you'll get started by using order dict getting started with order dict Python's order dict is a dictionary subclass that preserves the order in which key value pairs commonly known as items are inserted into the dictionary when you iterate over an order dict object items are traversed in the original order when you update the value of an existing key then the order remains unchanged if you remove an item and reinsert it then the item is being added at the end of the dictionary being a dictionary subclass means that it inherits all the methods a regular dictionary provides order dict also has additional features that you'll learn about in this course in this section you'll learn the basics of creating and using order dict objects in your code unlike standard dictionaries order dict isn't a built-in type so the first step to create an order dict object is to import the class from collections there are several ways to create order dictionaries and most of them are identical to how you create a regular dictionary object for example you can create an empty order dictionary by instantiating the class without arguments first you import all the decks from collections then you create an empty order dictionary by instantiating order dict without providing arguments to the Constructor you can add key value pairs to the dictionary by providing a key in square brackets and assigning a value to that key when you reference numbers you get an iterable of key value pairs that holds items in the same order they were inserted into the dictionary you can also pass an iterable of items as an argument to the Constructor of order dict when you use a sequence such as a list or Tuple the order of the items in the resulting order dictionary matches the original order of items in the input sequence if you use a set then the final order of items is unknown until the order dict is created if you use a regular dictionary as an initializer to an ordered dict object and you're on python 3.6 or Beyond then you get the behavior seen on screen the order of items in the order dict objects matches the order in the original dictionary on the other hand if you're using a version of python lower than 3.6 then the order of items is unknown since dictionaries in Python 3.5 don't remember the order of their items you don't know the order in the resulting order dictionary until the object is created from this point on the order is maintained you can also create an order dictionary by passing keyword arguments to the class Constructor since python 3.6 functions retain the order of keyword arguments passed in a call so the order of the items in the order date matches the order in which you pass the keyword arguments to the Constructor in earlier python versions that order is unknown finally order dict also provides the from Keys method which creates a new dictionary from an iterable of keys and sets all its values to a common value here you create an ordered dictionary using a list of keys as a starting point the second argument to from Keys provides a single value 0 To All the items in the dictionary since order dict is a mutable data structure you can perform mutating operations on its instances you can insert new items update and remove existing items and so on if you insert a new item into an existing order dictionary then the item is added to the end of the dictionary the newly added item 4 is placed at the end of the underlying dictionary so the order of the existing items remains unaffected and the dictionary keeps the insertion order if you delete an item from an existing order dictionary and insert that same item again then the new instance of the item is placed at the end of the dictionary if you remove the one item and insert a new instance of the same item then the new item is added to the end of the underlying dictionary if you reassign or update the value of an existing key value pair in an ordered dictionary object then the key maintains its position but gets a new value if you update the value of a given key in an ordered dictionary then the key isn't moved but assign the new value in place in the same way if you use update to modify the value of an existing key value pair then the dictionary remembers the position of the key and assigns the updated value to it in the next section of the course you'll deepen your knowledge of all the debts by looking at iteration iterating over an ordered debt just as with regular dictionaries you can iterate through an ordered direct object using several tools and techniques you can iterate over the keys directly or you can use dictionary methods such as items keys and values this Loop iterates over the keys of numbers directly this Loop iterates over items this Loop iterates over keys and this Loop iterates over values another important feature that order dict has provided since python 3.5 is the items keys and values support reverse iteration using reversed this feature was added to regular dictionaries in Python 3.8 so if your code uses it then your backwards compatibility is much more restricted with normal dictionaries you can use reversed with the items keys and values of an order dict object regular dictionaries also support reverse iteration however if you try to use reversed with a regular dictionary object in a python version lower than 3.8 then you get a type error if you need to iterate over the items in a dictionary in reverse order then order dict is a good Ally using a regular dictionary dramatically reduces your backwards compatibility because reverse iteration wasn't added to regular dictionaries until python 3.8 in the next section of the course you'll take a look at some of the unique features of order dict exploring unique features of order dict since python 3.6 regular dictionaries have kept their items in the same order that they were inserted into the underlying dictionary this limits the usefulness of all the dict as you've seen so far however orderdick provides some unique features that you can't find in a regular dictionary with an ordered dictionary you have access to these extra and enhanced methods move to end allows you to move an existing item either to the end or the beginning of a dictionary pop item is an enhanced variation of its dictionary counterpart that allows you to remove and return an item from either the end or the beginning of the underlying order dictionary order dict and dict also behave differently when they're tested for equality specifically when you compare order dictionaries the order of items matters that's not the case with regular dictionaries finally order deck provides an attribute called underdict that you can't find in a regular dictionary instance this attribute allows you to add custom writable attributes to an existing order dictionary one of the most useful unique features of order dict is that it has an extra method called move to end this method allows you to move existing items to either the end or the beginning of the underlying dictionary so it's a great tool for reordering when you use move to end you can supply two arguments key holds the key that identifies the item that you want to move if key doesn't exist then you get a key error last holds a Boolean value that defines to which end of the dictionary you want to move the item it defolds to True which means the item will be moved to the end or right side of the dictionary false means the item will be moved to the front or left side of the dictionary on-screen is an example of how to use move to end with a key argument and relying on the default value of last when you call move to end with a key as an argument you move the key value pair at hand to the end of the dictionary that's why one is now in the last position note that the rest of the items remain in the original order if you pass false to last then you're moving the item to the beginning here you move one back to the beginning of the dictionary this provides an interesting and Powerful feature for example with move to end you can sort an order dictionary by keys here you first create an order dictionary letters the for Loop iterates over the sorted keys and moves every item to the end of the dictionary when the loop finishes the order dictionary has its items sorted by keys sorting the dictionary by values would be an interesting exercise so let's take a look at one where you could achieve this here a Lambda expression is used to provide the key giving access to the value of each item as you can see the dictionary is now ordered by the value of the key if you want to learn more about Lambda Expressions check out this real python course which covers them in detail another interesting feature of order dict is its enhanced version of Pop item by default pop item removes and returns an item in last in first out order in other words it removes items from the right end of the ordered dictionary here you remove all the items from numbers using pop item every call to this method removes a single item from the end of the underlying dictionary if you call Pop item on an empty dictionary then you get a key error up to this point pop item behaves the same as in regular dictionaries in order dict however Pop item also accepts a Boolean argument called last which defaults to true if you set last to false then pop item removes the items in first in first out order in other words it removes items from the beginning of the dictionary once again the last call to pop item raises a key error because the underlying dictionary is already empty in the next section of the course you'll deepen your knowledge of all the debts by looking at how to test for equality between dictionaries

Original Description

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. This is a portion of the complete course, which you can find here: https://realpython.com/courses/ordereddict-python/ The rest of the course covers how to: - Testing for Equality and Adding Attributes - Merging and Updating Dictionaries With Operators - Performance Differences - Building a Dictionary-Based Queue
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Real Python · Real Python · 0 of 60

← Previous Next →
1 A better Python REPL – bpython vs python interpreter
A better Python REPL – bpython vs python interpreter
Real Python
2 Introducing large-type.com – A Utility Website
Introducing large-type.com – A Utility Website
Real Python
3 Reading Hacker News Without Wasting Tons of Time
Reading Hacker News Without Wasting Tons of Time
Real Python
4 Forward References and Python 3 Type Hints
Forward References and Python 3 Type Hints
Real Python
5 Using Sublime Text as your Git Editor
Using Sublime Text as your Git Editor
Real Python
6 Python Code Linting and Auto-Complete for Sublime Text
Python Code Linting and Auto-Complete for Sublime Text
Real Python
7 Make your Python Code More Readable with Custom Exceptions
Make your Python Code More Readable with Custom Exceptions
Real Python
8 Write Better Tests with Sublime Text's Split Layout Feature
Write Better Tests with Sublime Text's Split Layout Feature
Real Python
9 How to Use Sublime Text from the Command Line
How to Use Sublime Text from the Command Line
Real Python
10 Rename Variables with Multiple Selection in Sublime Text
Rename Variables with Multiple Selection in Sublime Text
Real Python
11 Sublime Text Settings for Writing PEP 8 Python
Sublime Text Settings for Writing PEP 8 Python
Real Python
12 Write Cleaner Python with Sublime Text's Indent Guides
Write Cleaner Python with Sublime Text's Indent Guides
Real Python
13 Sublime Text Whitespace Settings for Python Development
Sublime Text Whitespace Settings for Python Development
Real Python
14 Function Argument Unpacking in Python
Function Argument Unpacking in Python
Real Python
15 Python Code Review: Debugging and Refactoring "Conway's Game of Life" +  Automated Tests
Python Code Review: Debugging and Refactoring "Conway's Game of Life" + Automated Tests
Real Python
16 Using "get()" to Return a Default Value from a Python Dict
Using "get()" to Return a Default Value from a Python Dict
Real Python
17 A Python Shorthand for Swapping Two Variables
A Python Shorthand for Swapping Two Variables
Real Python
18 Python Code Review: Refactoring a Web Scraper, PEP 8 Style Guide Compliance, requirements.txt
Python Code Review: Refactoring a Web Scraper, PEP 8 Style Guide Compliance, requirements.txt
Real Python
19 Click & Jump to Test Failures from the Command Line (iTerm2)
Click & Jump to Test Failures from the Command Line (iTerm2)
Real Python
20 Setting up Sublime Text for Python Developers
Setting up Sublime Text for Python Developers
Real Python
21 Sublime Text + Python Guide Overview
Sublime Text + Python Guide Overview
Real Python
22 Python Code Review: Adding Pytest Tests to an Existing Python Web Scraper
Python Code Review: Adding Pytest Tests to an Existing Python Web Scraper
Real Python
23 Type-Checking Python Programs With Type Hints and mypy
Type-Checking Python Programs With Type Hints and mypy
Real Python
24 A Shorthand for Merging Dictionaries in Python 3.5+
A Shorthand for Merging Dictionaries in Python 3.5+
Real Python
25 Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt
Python Code Review Flask Web Security Tutorial + Virtualenvs, requirements.txt
Real Python
26 My Python Code Looks Ugly and Confusing – Help!
My Python Code Looks Ugly and Confusing – Help!
Real Python
27 Setting Up a Programmer Portfolio/Developer Blog – How To Get Started
Setting Up a Programmer Portfolio/Developer Blog – How To Get Started
Real Python
28 Do I Need a GitHub/GitLab/Bitbucket Profile as a Developer?
Do I Need a GitHub/GitLab/Bitbucket Profile as a Developer?
Real Python
29 Programmer Portfolio – Example and Walkthrough
Programmer Portfolio – Example and Walkthrough
Real Python
30 How to Get Your 1st Speaking Gig at a Tech Conference
How to Get Your 1st Speaking Gig at a Tech Conference
Real Python
31 How to Build Your Public Speaking Skills as a Developer
How to Build Your Public Speaking Skills as a Developer
Real Python
32 The Object-oriented Version of "Spaghetti Code" is "Lasagna Code" ?!
The Object-oriented Version of "Spaghetti Code" is "Lasagna Code" ?!
Real Python
33 Setting up Sublime Text for Python Developers – Lesson #1
Setting up Sublime Text for Python Developers – Lesson #1
Real Python
34 Cool New Features in Python 3.6
Cool New Features in Python 3.6
Real Python
35 "is" vs "==" in Python – What's the Difference? (And When to Use Each)
"is" vs "==" in Python – What's the Difference? (And When to Use Each)
Real Python
36 Emulating switch/case Statements in Python with Dictionaries
Emulating switch/case Statements in Python with Dictionaries
Real Python
37 Python Function Argument Unpacking Tutorial (* and ** Operators)
Python Function Argument Unpacking Tutorial (* and ** Operators)
Real Python
38 What Code Should I Put On My GitHub/GitLab/BitBucket Profile?
What Code Should I Put On My GitHub/GitLab/BitBucket Profile?
Real Python
39 A Crazy Python Dictionary Expression ?!
A Crazy Python Dictionary Expression ?!
Real Python
40 String Conversion in Python: When to Use __repr__ vs __str__
String Conversion in Python: When to Use __repr__ vs __str__
Real Python
41 Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Method Types in Python OOP: @classmethod, @staticmethod, and Instance Methods
Real Python
42 Optional Arguments in Python With *args and **kwargs
Optional Arguments in Python With *args and **kwargs
Real Python
43 Python Context Managers and the "with" Statement (__enter__ & __exit__)
Python Context Managers and the "with" Statement (__enter__ & __exit__)
Real Python
44 Installing Python Packages with pip and virtualenv / venv
Installing Python Packages with pip and virtualenv / venv
Real Python
45 "For Each" Loops in Python with enumerate() and range()
"For Each" Loops in Python with enumerate() and range()
Real Python
46 Python Code Review: LibreOffice Automation and the Python Standard Library
Python Code Review: LibreOffice Automation and the Python Standard Library
Real Python
47 Managing Python Dependencies With Pip and Virtual Environments – Lesson #1
Managing Python Dependencies With Pip and Virtual Environments – Lesson #1
Real Python
48 Python Tutorial: List Comprehensions Step-By-Step
Python Tutorial: List Comprehensions Step-By-Step
Real Python
49 Leveraging Python's Implicit "return None" Statements
Leveraging Python's Implicit "return None" Statements
Real Python
50 What's the meaning of underscores (_ & __) in Python variable names?
What's the meaning of underscores (_ & __) in Python variable names?
Real Python
51 Python Data Structures: Sets, Frozensets, and Multisets (Bags)
Python Data Structures: Sets, Frozensets, and Multisets (Bags)
Real Python
52 Writing automated tests for Python command-line apps and scripts
Writing automated tests for Python command-line apps and scripts
Real Python
53 How to find great Python packages on PyPI, the Python Package Repository
How to find great Python packages on PyPI, the Python Package Repository
Real Python
54 Immutable vs Mutable Objects in Python
Immutable vs Mutable Objects in Python
Real Python
55 PyPI vs Warehouse, the Next-Generation Python Package Repository
PyPI vs Warehouse, the Next-Generation Python Package Repository
Real Python
56 pep8.org — The Prettiest Way to View the PEP 8 Python Style Guide
pep8.org — The Prettiest Way to View the PEP 8 Python Style Guide
Real Python
57 My Experience at PyCon 2017 in Portland
My Experience at PyCon 2017 in Portland
Real Python
58 Pylint Tutorial – How to Write Clean Python
Pylint Tutorial – How to Write Clean Python
Real Python
59 "Reverse a List in Python" Tutorial: Three Methods & How-to Demos
"Reverse a List in Python" Tutorial: Three Methods & How-to Demos
Real Python
60 Python Refactoring: "while True" Infinite Loops & The "input" Function
Python Refactoring: "while True" Infinite Loops & The "input" Function
Real Python

The video teaches the unique features of Python's OrderedDict and how it can be used to create ordered dictionaries with additional features. It covers the OrderedDict's API, its ability to remember the order of items by their insertion order, and how it provides valuable features such as explicit signaling and control over item order. By watching this video, viewers can learn how to use OrderedDict to solve problems that require ordered data structures.

Key Takeaways
  1. Import the OrderDict class from the collections module
  2. Create an empty OrderDict object by instantiating the class without arguments
  3. Add key-value pairs to the OrderDict object by providing a key in square brackets and assigning a value to that key
  4. Reference the OrderDict object to get an iterable of key-value pairs that holds items in the same order they were inserted into the dictionary
  5. Pass an iterable of items as an argument to the constructor of OrderDict
  6. Move an existing item to the end or beginning of a dictionary
  7. Add custom writable attributes to an existing order dictionary
  8. Remove and return an item from the end or beginning of the dictionary
💡 The OrderedDict's ability to remember the order of items by their insertion order and provide explicit signaling and control over item order makes it a valuable tool for solving problems that require ordered data structures.

Related Reads

📰
The Run-Length Encoding Trick: How Simple Strings Get Compressed
Learn how Run-Length Encoding (RLE) compresses simple strings, a fundamental technique in programming and data compression, and apply it to optimize storage and transmission of data
Medium · Programming
📰
75 Days of Leetcode — Day 4: #238 — Product of Array Except Self
Solve the Product of Array Except Self problem on LeetCode to improve coding skills and learn array manipulation techniques
Medium · AI
📰
I implemented the algorithm that broke the sorting barrier. Dijkstra still wins.
Learn how the author implemented an algorithm that broke the sorting barrier and compare its performance with Dijkstra's algorithm
Medium · Programming
📰
I implemented the algorithm that broke the sorting barrier. Dijkstra still wins.
Implementing an algorithm that breaks the sorting barrier still can't beat Dijkstra's algorithm in practice, highlighting the importance of real-world testing and optimization.
Medium · Python
Up next
Stump Grinder Carbide Wheel Grinds Hardwood To Chips
Innoforge Studio
Watch →