OrderedDict
- Python course
- Intermediate
- Lesson 90/116
- 5 min
Learn ordered dicts with OrderedDict.
OrderedDict
OrderedDict is a dictionary type that keeps the insertion order of keys. In Python 3.7+ the standard dict also keeps order, but OrderedDict offers extra methods.
The most important extra method is move_to_end(key, last=True). It moves a key to the end (default) or to the beginning. popitem(last=True) removes the last or first item. These methods are useful for cache or ordered-queue applications.
The move_to_end method
With move_to_end you move a key to the end or beginning of the dict. By default the key goes to the end; with last=False it moves to the beginning. This is often used in LRU (least recently used) cache structures.
Example: od = OrderedDict()\nod["a"] = 1\nod["b"] = 2\nod.move_to_end("a"). After this code the order is b, a. With list(od.keys()) you can see the keys as an ordered list.
Practice Reorder keys with OrderedDict
Start with from collections import OrderedDict. Create an OrderedDict with od = OrderedDict(). Add two keys with od["a"] = 1 and od["b"] = 2. Move a to the end with od.move_to_end("a"). Then print the keys with print(list(od.keys())).
Starter code
# Reorder keys with OrderedDictSample solution
# Reorder keys with OrderedDict
from collections import OrderedDict
od = OrderedDict()
od["a"] = 1
od["b"] = 2
od.move_to_end("a")
print(list(od.keys()))Expected output
['b', 'a']
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which module does OrderedDict come from?
- functools
- typing
- itertools
- collections Correct answer
Explanation: OrderedDict is in the collections module.
2 move_to_end call
od = OrderedDict()
od["a"] = 1
od["b"] = 2
od.____("a")
print(list(od.keys()))
od = OrderedDict()
od["a"] = 1
od["b"] = 2
od.move_to_end("a")
print(list(od.keys()))
Explanation: move_to_end moves the key to the end.
3 Match the OrderedDict parts
| Term | Meaning |
|---|---|
OrderedDict |
Ordered dict |
move_to_end |
Moves a key |
popitem |
Removes an item |
collections |
Module |