PYTHON

Create Readable Data Records with Named Tuples

Learn to use `collections.namedtuple` to create lightweight, immutable object-like data structures. Improve code readability and maintainability when handling database rows or API responses.

from collections import namedtuple

# Define a named tuple for a User record
User = namedtuple('User', ['id', 'username', 'email'])

# Create instances of the User named tuple
user1 = User(id=1, username='alice', email='[email protected]')
user2 = User(2, 'bob', '[email protected]') # Positional arguments also work

print(f"User 1: {user1}")
print(f"User 2 username: {user2.username}")
print(f"User 1 ID: {user1.id}")

# Accessing elements by index (like a regular tuple)
print(f"User 1 email by index: {user1[2]}")

# Named tuples are immutable
try:
    user1.username = 'alicia'
except AttributeError as e:
    print(f"Error trying to modify a named tuple: {e}")

# Converting named tuple to dictionary
user1_dict = user1._asdict()
print(f"User 1 as dict: {user1_dict}")

# Use case: Parsing API response data
ApiResponse = namedtuple('ApiResponse', ['status_code', 'data', 'message'])
response_data = {'status_code': 200, 'data': {'name': 'Product A', 'price': 100}, 'message': 'Success'}
api_response = ApiResponse(**response_data) # Unpack dictionary into named tuple
print(f"API response status: {api_response.status_code}")
print(f"API response product name: {api_response.data['name']}")
How it works: `collections.namedtuple` allows you to create tuple subclasses with named fields. This provides the immutability and memory efficiency of tuples while enhancing readability by letting you access elements using dot notation (e.g., `user.username`) instead of integer indices. It's ideal for representing simple data records like database rows, API response objects, or configuration settings where you want a lightweight, self-documenting structure without the overhead of defining a full custom class.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs