OrderedDict

Order-preserving dictionaries

Interview Relevant: Legacy code understanding

OrderedDict

Dictionary that remembers insertion order.

Code Examples

OrderedDict for order-sensitive operations.

python
1from collections import OrderedDict
2
3# Note: Python 3.7+ dicts preserve order by default!
4# OrderedDict still useful for some operations
5
6od = OrderedDict()
7od["a"] = 1
8od["b"] = 2
9od["c"] = 3
10
11# Move to end
12od.move_to_end("a")  # {"b": 2, "c": 3, "a": 1}
13od.move_to_end("c", last=False)  # Move to beginning
14
15# Pop from ends
16od.popitem()              # Pop last
17od.popitem(last=False)    # Pop first
18
19# OrderedDict equality considers order
20OrderedDict([("a", 1), ("b", 2)]) == OrderedDict([("b", 2), ("a", 1)])
21# False (different order)
22
23# Regular dict equality ignores order
24{"a": 1, "b": 2} == {"b": 2, "a": 1}  # True

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In