0Pricing
Python Academy · Lesson

namedtuple and OrderedDict

Other handy collections.

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)

All lessons in this course

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