namedtuples

they should be used more

Easy-to-create, lightweight object types.
They allow to fetch an element of the tuple by name, eg person.last_name if last_name would be an element of that namedtuple.
Namedtuples are backwards compatible with normal tuples - so can be called as person[0].

Usage

from collections import namedtuple

# Define namedtupe format and names
person = namedtuple('Person', ['first', 'last'])

# Create a namedtuple
x = person(first='Paul', last='Atreides')

# Call elements of the namedtuple with .
print(x.last)

outputs:

'Atreides'

or return as dict with x._asdict():

print(x._asdict())

outputs:

{'first': 'Paul', 'last': 'Atreides'}

Snippets

Sort list of namedtuples by key

from operator import attrgetter

sorted(list_object, key=attrgetter('release_date'))

links

social