|
| 1 | +""" |
| 2 | +OrderedDict operations in Python. |
| 3 | +
|
| 4 | +This module demonstrates the usage of collections.OrderedDict and its differences from regular dict: |
| 5 | +- OrderedDict maintains the order of item insertion |
| 6 | +- Key differences between OrderedDict and regular dict |
| 7 | +- Common OrderedDict operations and methods |
| 8 | +""" |
| 9 | + |
| 10 | +from collections import OrderedDict |
| 11 | + |
| 12 | +# When to use OrderedDict vs regular dict: |
| 13 | +# Use OrderedDict when: |
| 14 | +# - Order of insertion needs to be preserved and is meaningful |
| 15 | +# - You need equality comparisons that consider order |
| 16 | +# - You need to move items to the start/end of the dictionary |
| 17 | + |
| 18 | +# Use regular dict when: |
| 19 | +# - Order is not important |
| 20 | +# - Memory efficiency is a concern |
| 21 | +# - You're using Python 3.7+ and just need basic insertion order preservation |
| 22 | +# (regular dict maintains insertion order since Python 3.7) |
| 23 | + |
| 24 | +# Key differences between dict and OrderedDict: |
| 25 | +# 1. Order matters in equality comparison |
| 26 | +dict1 = {"a": 1, "b": 2} |
| 27 | +dict2 = {"b": 2, "a": 1} |
| 28 | +print(dict1 == dict2) # Output: True (order doesn't matter for regular dict) |
| 29 | + |
| 30 | +odict1 = OrderedDict([("a", 1), ("b", 2)]) |
| 31 | +odict2 = OrderedDict([("b", 2), ("a", 1)]) |
| 32 | +print(odict1 == odict2) # Output: False (order matters for OrderedDict) |
| 33 | + |
| 34 | +# 2. Memory usage |
| 35 | +# OrderedDict uses more memory than regular dict as it maintains a doubly-linked list |
| 36 | + |
| 37 | +# Creating an OrderedDict |
| 38 | +# OrderedDict remembers the order in which keys were inserted |
| 39 | +ordered_fruits = OrderedDict() |
| 40 | +ordered_fruits["apple"] = 100 |
| 41 | +ordered_fruits["banana"] = 200 |
| 42 | +ordered_fruits["orange"] = 150 |
| 43 | +# Output: OrderedDict([('apple', 100), ('banana', 200), ('orange', 150)]) |
| 44 | + |
| 45 | +# Creating from list of tuples |
| 46 | +items = [("a", 1), ("b", 2), ("c", 3)] |
| 47 | +ordered_dict = OrderedDict(items) |
| 48 | +# Output: OrderedDict([('a', 1), ('b', 2), ('c', 3)]) |
| 49 | + |
| 50 | +# Common operations (similar to regular dict) |
| 51 | +ordered_fruits["grape"] = 300 # Adding new element |
| 52 | +del ordered_fruits["apple"] # Removing element |
| 53 | +price = ordered_fruits.pop("banana") # Removing and returning value |
| 54 | + |
| 55 | +# OrderedDict specific operations |
| 56 | +# Moving element to end |
| 57 | +ordered_dict.move_to_end("a") |
| 58 | +# Output: OrderedDict([('b', 2), ('c', 3), ('a', 1)]) |
| 59 | + |
| 60 | +# Moving element to beginning |
| 61 | +ordered_dict.move_to_end("a", last=False) |
| 62 | +# Output: OrderedDict([('a', 1), ('b', 2), ('c', 3)]) |
0 commit comments