|
| Home |
|---|
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.
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.
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.
from collections import OrderedDict
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.
from collections import OrderedDict
data = OrderedDict()
data["a"] = 10
data["b"] = 20
data["c"] = 30
print(data)
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.
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.
from collections import OrderedDict
data = OrderedDict([
("name","Alice"),
("age",21),
("course","Python")
])
print(data)
OrderedDict([('name', 'Alice'), ('age', 21), ('course', 'Python')])
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.
from collections import OrderedDict
data = OrderedDict(x=1, y=2, z=3)
print(data)
OrderedDict([('x', 1), ('y', 2), ('z', 3)])
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.
from collections import OrderedDict
data = OrderedDict([
("a",10),
("b",20),
("c",30)
])
for key, value in data.items():
print(key, value)
a 10
b 20
c 30
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.
from collections import OrderedDict
data = OrderedDict([
("a",10),
("b",20),
("c",30)
])
for key in reversed(data):
print(key, data[key])
c 30
b 20
a 10
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.
from collections import OrderedDict
data = OrderedDict([
("a",10),
("b",20),
("c",30)
])
data.move_to_end("a")
print(data)
OrderedDict([('b', 20), ('c', 30), ('a', 10)])
Pass last=False to move a key to the beginning instead of the end.
from collections import OrderedDict
data = OrderedDict([
("a",10),
("b",20),
("c",30)
])
data.move_to_end("c", last=False)
print(data)
OrderedDict([('c', 30), ('a', 10), ('b', 20)])
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).
from collections import OrderedDict
data = OrderedDict([
("a",10),
("b",20),
("c",30)
])
data.popitem()
print(data)
OrderedDict([('a', 10), ('b', 20)])
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.
from collections import OrderedDict
data = OrderedDict([
("a",10),
("b",20),
("c",30)
])
data.popitem(last=False)
print(data)
OrderedDict([('b', 20), ('c', 30)])
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.
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)
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.
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.
from collections import OrderedDict
data = OrderedDict([
("a",10),
("b",20)
])
data.update({"a": 99, "c": 30})
print(data)
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+.
| 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 |
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.
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)
OrderedDict([('C', 3), ('A', 1)])
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.
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)
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.
move_to_end() to reorder existing keys, such as in LRU or MRU caching systemsmove_to_end() and never compare dictionaries for order-sensitive equalitycollections module before usemove_to_end() has no direct equivalent on a regular dictpopitem()'s default (last item) with the behavior of a regular dict's popitem(), which also removes the last item but without the last keyword argument
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.
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.
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.
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.
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.
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.
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.
Home Tutorial Online Live Trainings Contact Us © 2026 All rights reserved by www.PythonTutor.net