Python Academy · Lesson

namedtuple and OrderedDict

Other handy collections.

Lesson 4 of 413 steps

namedtuple and OrderedDict is a free Python Academy lesson on CoddyKit. This is lesson 4 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, and your progress syncs across the web and the CoddyKit app. The Python Academy course includes 4 lessons in total.

Two more handy collections

The collections module includes namedtuple for readable record-like tuples and OrderedDict for dictionaries with extra ordering methods.

Import them with from collections import namedtuple, OrderedDict.

from collections import namedtuple, OrderedDict
print(namedtuple)
print(OrderedDict)

Defining a namedtuple

namedtuple(name, fields) creates a new tuple subclass. You pass the type name and a list of field names. The result is a class you can instantiate.

from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 4)
print(p)

Access by name

The big win: read fields by name instead of cryptic index numbers, which makes code far more readable.

from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 4)
print(p.x)
print(p.y)

Still a tuple

A namedtuple is a real tuple, so indexing, unpacking, and iteration all still work.

from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 4)
print(p[0])
x, y = p
print(x + y)

Immutable but replaceable

Like all tuples, namedtuples are immutable. To get a modified copy, use ._replace(), which returns a new instance.

from collections import namedtuple
Point = namedtuple('Point', ['x', 'y'])
p = Point(3, 4)
q = p._replace(y=10)
print(p)
print(q)

Converting to a dict

._asdict() turns a namedtuple into a regular dictionary mapping field names to values.

from collections import namedtuple
Car = namedtuple('Car', ['make', 'year'])
c = Car('Toyota', 2026)
print(c._asdict())

Default values

Provide defaults when defining a namedtuple. Defaults apply to the rightmost fields, so you can omit them when creating instances.

from collections import namedtuple
User = namedtuple('User', ['name', 'role'], defaults=['guest'])
print(User('Alice'))
print(User('Bob', 'admin'))

Inspecting fields

The ._fields attribute lists the field names, useful for introspection or building generic code.

from collections import namedtuple
Color = namedtuple('Color', ['r', 'g', 'b'])
print(Color._fields)

OrderedDict basics

OrderedDict remembers insertion order. Since Python 3.7 regular dicts also keep order, but OrderedDict adds extra ordering methods you cannot get otherwise.

from collections import OrderedDict
od = OrderedDict()
od['first'] = 1
od['second'] = 2
print(od)

move_to_end

.move_to_end(key) shifts a key to the end (or the start with last=False). This is unique to OrderedDict and handy for LRU-style logic.

from collections import OrderedDict
od = OrderedDict(a=1, b=2, c=3)
od.move_to_end('a')
print(list(od.keys()))
od.move_to_end('c', last=False)
print(list(od.keys()))

Order-sensitive equality

Two OrderedDict objects are equal only if their items are in the same order. Plain dicts ignore order in comparisons.

from collections import OrderedDict
a = OrderedDict([('x', 1), ('y', 2)])
b = OrderedDict([('y', 2), ('x', 1)])
print(a == b)
print(dict(a) == dict(b))

Quick Check

How do you create a modified copy of a namedtuple, since it is immutable?

Recap: namedtuple and OrderedDict

Summary:

  • namedtuple(name, fields) makes readable, immutable records with named access.
  • Use ._replace() for modified copies and ._asdict() to convert to a dict.
  • OrderedDict keeps insertion order and adds .move_to_end().
  • OrderedDict equality is order-sensitive, unlike a plain dict.
from collections import namedtuple
Pt = namedtuple('Pt', ['x', 'y'])
print(Pt(1, 2)._asdict())
Free to start

Learn Python with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
76
Lessons
320

Frequently Asked Questions

Is the “namedtuple and OrderedDict” lesson free?

Yes — the full text of “namedtuple and OrderedDict” is free to read here on the web. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO. The Python Academy course includes 4 lessons in total.

What will I learn in “namedtuple and OrderedDict”?

Other handy collections. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Python Academy?

No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 4 of 4.

How long does the “namedtuple and OrderedDict” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Python Academy lesson?

Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Counter
  2. defaultdict
  3. deque
  4. namedtuple and OrderedDict
← Back to Python Academy