software-mariodiana
6/10/2014 - 9:23 PM

How to take the tuples returned from a database query and convert them into named tuples.

How to take the tuples returned from a database query and convert them into named tuples.

from collections import namedtuple

# Assume a previously executed query.
rows = cursor.fetchall()

# Index 0 of the metadata returned is the column name.
columns = [aColumn[0] for aColumn in cursor.description]
NamedRow = namedtuple('NamedRow', columns)

# A generator may help with larger datasets.
rows = (NamedRow(*aRow) for aRow in rows)
rows = tuple([aRow for aRow in rows])

first = rows[0]

# And, assume a column called Address.
print first.Address

# prints: 1313 Mockingbird Lane