Build an OrderedDict insertion order demo in Python 3

Demonstrate how OrderedDict preserves insertion order, how updates keep position, and how re-insertion moves keys to the end.

Easy Python 3.7+ Aug 9, 2026 Dictionaries & sets 13 views 0 copies

Python code

32 lines
Python 3.7+
from collections import OrderedDict

def demo_ordered_dict():
    # Create an OrderedDict and insert items in a specific order
    ordered = OrderedDict()
    ordered['banana'] = 3
    ordered['apple'] = 2
    ordered['cherry'] = 5
    ordered['date'] = 1

    print("Insertion order preserved:")
    for key, value in ordered.items():
        print(f"  {key}: {value}")

    # Modify an existing key (doesn't change its position)
    ordered['apple'] = 10
    print("\nAfter updating 'apple' to 10 (position stays):")
    print("  Keys order:", list(ordered.keys()))

    # Delete and re-insert moves it to the end
    del ordered['banana']
    ordered['banana'] = 7
    print("\nAfter deleting and re-inserting 'banana':")
    print("  Keys order:", list(ordered.keys()))

    # Regular dict also preserves insertion order in Python 3.7+
    reg_dict = {'x': 1, 'y': 2, 'z': 3}
    print("\nRegular dict in Python 3.7+ also preserves order:")
    print("  Keys order:", list(reg_dict.keys()))

if __name__ == "__main__":
    demo_ordered_dict()

Output

stdout
Insertion order preserved:
  banana: 3
  apple: 2
  cherry: 5
  date: 1

After updating 'apple' to 10 (position stays):
  Keys order: ['banana', 'apple', 'cherry', 'date']

After deleting and re-inserting 'banana':
  Keys order: ['apple', 'cherry', 'date', 'banana']

Regular dict in Python 3.7+ also preserves order:
  Keys order: ['x', 'y', 'z']

How it works

OrderedDict from the collections module is a dict subclass that explicitly guarantees insertion order. When you update an existing key's value, its position in the dictionary remains unchanged because the key already exists. Deleting a key and then re-inserting it appends it to the end, since it's treated as a new entry. Since Python 3.7, regular dictionaries also preserve insertion order as part of the language spec, making OrderedDict mostly useful for code that needs explicit compatibility or extra methods like move_to_end. The demo prints the order after each operation to make the behavior visible.

Common mistakes

  • Assuming updating a value changes key position — it doesn't
  • Forgetting that deleting and re-inserting moves the key to the end
  • Using OrderedDict when a regular dict would suffice in modern Python (3.7+)

Variations

  1. Use `ordered.move_to_end('apple')` to explicitly move an existing key to the end
  2. Reverse the order with `for key in reversed(ordered):` to iterate backwards

Real-world use cases

  • Maintaining a strict-order configuration where key sequence matters for serialization.
  • Building an LRU-style cache that tracks recency with re-insertion semantics.
  • Ensuring deterministic output order when dumping API responses or writing data files.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Dictionaries & sets

Related tutorials and quizzes for this topic.