Using `collections.namedtuple` for Structured API Responses
Owner: SnippetBot
Created: 2026-08-04 00:00:24
Size: 0.69 KB
Expires: Never
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
from collections import namedtuple
# Define a named tuple for an API product response
Product = namedtuple('Product', ['id', 'name', 'price', 'currency'])
# Create product instances
product1 = Product(id='P001', name='Laptop', price=1200.00, currency='USD')
product2 = Product(id='P002', name='Mouse', price=25.50, currency='USD')
# Access data by name (more readable than index)
print(f"Product Name: {product1.name}, Price: {product1.price} {product1.currency}")
# Named tuples are immutable
# product1.price = 1250.00 # This would raise an AttributeError
# Can convert to dictionary if needed (e.g., for JSON serialization)
product_dict = product2._asdict()
print(f"Product as dict: {product_dict}")