|
| 1 | +# OrderedDict in Python |
| 2 | +An OrderedDict is a dictionary subclass that remembers the order that keys were first inserted. |
| 3 | +The only difference between dict() and OrderedDict() is that: |
| 4 | + |
| 5 | +OrderedDict preserves the order in which the keys are inserted. A regular dict doesn’t track the |
| 6 | +insertion order, and iterating it gives the values in an arbitrary order. By contrast, the order the |
| 7 | +items are inserted is remembered by OrderedDict. |
| 8 | + |
| 9 | +_tags_: OrderedDict |
| 10 | + |
| 11 | +# Snippet |
| 12 | +``` |
| 13 | +# A Python program to demonstrate working of OrderedDict |
| 14 | + |
| 15 | +from collections import OrderedDict |
| 16 | + |
| 17 | +print("This is a Dict:\n") |
| 18 | +d = {} |
| 19 | +d['a'] = 1 |
| 20 | +d['b'] = 2 |
| 21 | +d['c'] = 3 |
| 22 | +d['d'] = 4 |
| 23 | + |
| 24 | +for key, value in d.items(): |
| 25 | + print(key, value) |
| 26 | + |
| 27 | +print("\nThis is an Ordered Dict:\n") |
| 28 | +od = OrderedDict() |
| 29 | +od['a'] = 1 |
| 30 | +od['b'] = 2 |
| 31 | +od['c'] = 3 |
| 32 | +od['d'] = 4 |
| 33 | + |
| 34 | +for key, value in od.items(): |
| 35 | + print(key, value) |
| 36 | +``` |
0 commit comments