← Back to Python

All Topics

Advertisement

Learn/Python/Advanced Python

Named Tuples and OrderedDict

Topic: Data Structures

Advertisement

Introduction

OrderedDict maintains insertion order, useful when order matters and you need dict features.

OrderedDict Basics

from collections import OrderedDict

od = OrderedDict()
od["a"] = 1
od["b"] = 2
od["c"] = 3

# Preserves insertion order
for k, v in od.items():
    print(k, v)

Move to End/Start

od = OrderedDict({"a": 1, "b": 2, "c": 3})

od.move_to_end("a")     # Move 'a' to end
od.move_to_end("a", last=False)  # Move to start

# Reverse iteration
for k in reversed(od):
    print(k)

Comparison

from collections import OrderedDict

od1 = OrderedDict({"a": 1, "b": 2})
od2 = OrderedDict({"b": 2, "a": 1})
d = {"a": 1, "b": 2}

# OrderedDict considers order
print(od1 == od2)  # False
print(dict(od1) == d)  # True (regular dict, Python 3.7+)

Practice Problems

  1. Create LRU cache with OrderedDict
  2. Track access order of items
  3. Implement most recently used tracking
  4. Reorder dictionary by values
  5. Serialize OrderedDict to JSON

Advertisement

Advertisement

Need More Practice?

Get personalized Python help from ChatWhole's AI-powered platform.

Get Expert Help →