Python Tutoring Online
 Home

Python OrderedDict: The Complete Guide with Examples

An OrderedDict is a specialized dictionary subclass in Python that remembers the exact order in which keys were inserted. It lives in the collections module and behaves like a normal dictionary in almost every way — you can index it, loop through it, add and remove keys — but it adds extra ordering-aware methods and comparison rules that a plain dict does not have.

This guide covers everything you need to know about OrderedDict: how to create one, how it differs from a regular dictionary in Python 3.7+, every method it exposes, real-world use cases like LRU caches, performance considerations, and answers to the most common questions developers search for.

Need Help Learning Python?

Understanding specialized dictionary types like OrderedDict helps when working with real-world data structures, interview questions, and production codebases.

Advanced dictionary tools like OrderedDict and defaultdict are widely used in caching layers, JSON serialization, and configuration management.

Get Python Tutoring Help

What Is OrderedDict and Why Does It Exist?

Before Python 3.7, the built-in dict type did not guarantee any particular order when you iterated over its keys. Two dictionaries created with the same key-value pairs, inserted in the same sequence, could theoretically print their items in different orders depending on internal hashing. This made certain algorithms — caching, deduplication, ordered serialization — unreliable.

OrderedDict was introduced in Python 2.7 and 3.1 specifically to solve this problem. It is implemented as a doubly linked list combined with a hash table, which lets it track insertion order efficiently while still offering O(1) average-case lookup, insertion, and deletion — the same performance profile as a regular dictionary.

Since Python 3.7, regular dictionaries also preserve insertion order as a language guarantee. This raises a common question: if regular dicts are ordered now, why use OrderedDict at all? The answer is that OrderedDict still offers behavior a plain dict does not — most importantly, order-sensitive equality checks and the move_to_end() method, both covered below.

Importing OrderedDict

OrderedDict is part of Python's built-in collections module, so no external installation is required. Import it once at the top of your file before using it.

Python
from collections import OrderedDict

Creating an Ordered Dictionary

An OrderedDict can be created the same way as a normal dictionary — either empty and populated afterward, or filled directly. The key guarantee is that the order items are added is the order they will appear in when the dictionary is printed or iterated.

Python
from collections import OrderedDict

data = OrderedDict()

data["a"] = 10
data["b"] = 20
data["c"] = 30

print(data)

Output


OrderedDict([('a', 10), ('b', 20), ('c', 30)])

Notice that OrderedDict's repr() looks different from a normal dict — it prints as OrderedDict([...]) with a list of tuples rather than curly braces. This is intentional: it makes the ordering explicit and unambiguous when debugging.

Creating OrderedDict from a List of Tuples

OrderedDict can also be constructed directly from an iterable of key-value pairs, such as a list of tuples. This is a common pattern when converting data from CSV rows, database query results, or API responses into an ordered structure.

Python
from collections import OrderedDict

data = OrderedDict([
("name","Alice"),
("age",21),
("course","Python")
])

print(data)

Output


OrderedDict([('name', 'Alice'), ('age', 21), ('course', 'Python')])

Creating OrderedDict with Keyword Arguments

You can also build an OrderedDict using keyword arguments, similar to a regular dict. Keep in mind that keyword argument order is preserved in Python 3.7+, so this works reliably in modern Python versions.

Python
from collections import OrderedDict

data = OrderedDict(x=1, y=2, z=3)

print(data)

Output


OrderedDict([('x', 1), ('y', 2), ('z', 3)])

Iterating Through OrderedDict

Ordered dictionaries preserve insertion order when iterating with .items(), .keys(), or .values(). This ensures predictable, repeatable results when processing data — critical for tasks like generating reports or exporting data in a fixed column order.

Python
from collections import OrderedDict

data = OrderedDict([
("a",10),
("b",20),
("c",30)
])

for key, value in data.items():
    print(key, value)

Output


a 10
b 20
c 30

Reversing Iteration Order with reversed()

OrderedDict supports the built-in reversed() function directly, letting you walk through items from the most recently inserted to the earliest, without manually reversing a list first. Regular dicts have also supported reversed() since Python 3.8, but OrderedDict has offered it since its original release.

Python
from collections import OrderedDict

data = OrderedDict([
("a",10),
("b",20),
("c",30)
])

for key in reversed(data):
    print(key, data[key])

Output


c 30
b 20
a 10

Reordering Elements with move_to_end()

The move_to_end() method moves an existing key to either the end or the beginning of the dictionary without affecting its associated value. This is the single most useful feature OrderedDict offers over a regular dict, and it has no built-in equivalent in plain dictionaries. It is heavily used when implementing caching systems, priority queues, and "recently used" tracking.

Python
from collections import OrderedDict

data = OrderedDict([
("a",10),
("b",20),
("c",30)
])

data.move_to_end("a")

print(data)

Output


OrderedDict([('b', 20), ('c', 30), ('a', 10)])

Pass last=False to move a key to the beginning instead of the end.

Python
from collections import OrderedDict

data = OrderedDict([
("a",10),
("b",20),
("c",30)
])

data.move_to_end("c", last=False)

print(data)

Output


OrderedDict([('c', 30), ('a', 10), ('b', 20)])

Removing Items with popitem()

OrderedDict supports an order-aware version of popitem(). By default it removes and returns the last inserted item — behaving like a stack (LIFO) — but it can also be told to remove the first inserted item, behaving like a queue (FIFO).

Python
from collections import OrderedDict

data = OrderedDict([
("a",10),
("b",20),
("c",30)
])

data.popitem()

print(data)

Output


OrderedDict([('a', 10), ('b', 20)])

Removing the First Item

Setting last=False removes the oldest item instead of the newest — the key behavior that makes OrderedDict so useful for FIFO queues and LRU cache eviction.

Python
from collections import OrderedDict

data = OrderedDict([
("a",10),
("b",20),
("c",30)
])

data.popitem(last=False)

print(data)

Output


OrderedDict([('b', 20), ('c', 30)])

Order-Sensitive Equality Comparisons

This is one of the most important — and most overlooked — differences between OrderedDict and a regular dict. Two regular dictionaries are considered equal if they contain the same keys and values, regardless of order. Two OrderedDict instances, however, are only equal if their keys and values match and appear in the same order.

Python
from collections import OrderedDict

od1 = OrderedDict([("a",1),("b",2)])
od2 = OrderedDict([("b",2),("a",1)])

d1 = {"a":1, "b":2}
d2 = {"b":2, "a":1}

print(od1 == od2)
print(d1 == d2)

Output


False
True

This distinction matters when you need to verify that two data structures not only contain the same information but were built or processed in the same sequence — for example, comparing two configuration files or two API responses for exact structural equality.

Updating and Copying an OrderedDict

Like regular dictionaries, OrderedDict supports .update() and .copy(). Updating an existing key does not change its position in the order; only new keys are appended at the end.

Python
from collections import OrderedDict

data = OrderedDict([
("a",10),
("b",20)
])

data.update({"a": 99, "c": 30})

print(data)

Output


OrderedDict([('a', 99), ('b', 20), ('c', 30)])

Notice that key "a" keeps its original position even though its value changed. This "update in place, insert at end" rule is the same behavior a regular dict follows in Python 3.7+.

OrderedDict vs Regular Dictionary

Feature OrderedDict Regular Dictionary
Insertion Order Preserved Guaranteed since introduction Guaranteed in Python 3.7+
move_to_end() method Yes Not available
popitem(last=False/True) Yes, order-aware popitem() removes last item only (no order argument)
Order-sensitive equality (==) Yes — order matters No — only keys/values matter
Memory usage Higher, due to linked-list overhead Lower
Performance Slightly slower for inserts/deletes historically; comparable in modern CPython Marginally faster in most benchmarks
Module collections Built-in
Best For Explicit order semantics, reordering, LRU caches General-purpose key-value storage

Practical Example: LRU Cache Simulation

OrderedDict is a textbook tool for implementing a Least Recently Used (LRU) cache. Whenever an item is accessed, it is moved to the end to mark it as "recently used." When the cache exceeds its size limit, the item at the front — the least recently used — is evicted.

Python
from collections import OrderedDict

cache = OrderedDict()

cache["A"] = 1
cache["B"] = 2
cache["C"] = 3

cache.move_to_end("A")

cache.popitem(last=False)

print(cache)

Output


OrderedDict([('C', 3), ('A', 1)])

Practical Example: Building a Simple LRU Cache Class

Combining move_to_end() and popitem(last=False), you can build a small, self-contained LRU cache with a fixed capacity in just a few lines.

Python
from collections import OrderedDict

class LRUCache:
    def __init__(self, capacity):
        self.cache = OrderedDict()
        self.capacity = capacity

    def get(self, key):
        if key not in self.cache:
            return -1
        self.cache.move_to_end(key)
        return self.cache[key]

    def put(self, key, value):
        if key in self.cache:
            self.cache.move_to_end(key)
        self.cache[key] = value
        if len(self.cache) > self.capacity:
            self.cache.popitem(last=False)

lru = LRUCache(2)
lru.put("a", 1)
lru.put("b", 2)
lru.get("a")
lru.put("c", 3)

print(lru.cache)

Output


OrderedDict([('a', 1), ('c', 3)])

Here, key "b" was evicted because it was the least recently used once the cache exceeded its capacity of 2. This exact pattern appears in Python's own functools.lru_cache implementation and in many real-world caching layers.

When to Use OrderedDict

When You Probably Don't Need OrderedDict

Common Beginner Mistakes

Frequently Asked Questions

Is OrderedDict still necessary in Python 3.7+?

Not for basic order preservation — regular dicts handle that automatically now. OrderedDict is still worth using when you need move_to_end(), order-sensitive equality, or want to make the ordering requirement explicit and self-documenting in your code.

Is OrderedDict faster or slower than a regular dict?

In modern CPython, the performance gap has narrowed significantly, but OrderedDict generally uses more memory and can be marginally slower for insertions and deletions because of the extra doubly linked list it maintains to track order.

Can you convert a regular dict to an OrderedDict?

Yes. Simply pass the dictionary into the OrderedDict constructor: OrderedDict(my_dict). Since Python 3.7+ dicts already preserve order, the resulting OrderedDict will reflect the same order as the original.

Does JSON support OrderedDict?

Python's json module can decode JSON objects into an OrderedDict using json.loads(text, object_pairs_hook=OrderedDict), which is useful when the order of keys in the source JSON must be preserved exactly.

What is the time complexity of OrderedDict operations?

Insertion, deletion, and lookup are all O(1) on average, the same as a regular dict. move_to_end() and order-aware popitem() are also O(1), since they operate directly on the internal linked list.

Does OrderedDict support dictionary comprehensions?

Not directly with the same syntax as a dict comprehension, since that syntax always produces a regular dict. You can, however, wrap a comprehension's result in OrderedDict(...) to convert it.

Related Python Dictionary Tutorials




Stuck Learning Python?

Struggling with Python syntax, assignments or debugging errors? Learning alone can be frustrating.

Get 1-on-1 Python tutoring and learn faster with clear explanations, real examples and live help.

    Get Python Tutoring

PythonTutor.net

Home    Tutorial     Online Live Trainings    Contact Us           © 2026 All rights reserved by www.PythonTutor.net