PYTHON
Structured Data with collections.namedtuple
Define lightweight, immutable object-like structures for tabular data or API records using Python's `collections.namedtuple` for readability and attribute access.
from collections import namedtuple
# Define a namedtuple for a User
User = namedtuple('User', ['id', 'username', 'email'])
# Create instances of User
user1 = User(id=1, username='alice_dev', email='[email protected]')
user2 = User(2, 'bob_coder', '[email protected]') # Positional arguments also work
print(f"User 1: {user1}")
print(f"User 2 username: {user2.username}")
print(f"User 1 email: {user1.email}")
# Accessing fields (like a tuple)
print(f"User 1 ID (index 0): {user1[0]}")
# Namedtuples are immutable
try:
user1.username = 'new_alice'
except AttributeError as e:
print(f"Error trying to modify: {e}")
# Convert to dictionary
print(f"User 1 as dict: {user1._asdict()}")
# Expected output:
# User 1: User(id=1, username='alice_dev', email='[email protected]')
# User 2 username: bob_coder
# User 1 email: [email protected]
# User 1 ID (index 0): 1
# Error trying to modify: can't set attribute
# User 1 as dict: {'id': 1, 'username': 'alice_dev', 'email': '[email protected]'}
How it works: `collections.namedtuple` allows you to create tuple subclasses with named fields. This provides the immutability and memory efficiency of tuples while offering the readability of accessing elements by name (e.g., `user.username` instead of `user[1]`). It's excellent for representing structured records from databases or API responses where you want a lightweight, predictable, and self-documenting data structure without the overhead of a full class definition, and when immutability is desired.