w3resource

Python Namedtuples: To Create Lightweight Object Types

Introduction to Python Namedtuples

This tutorial covered the basics of using namedtuples in Python, highlighting their creation, default values, conversion to dictionaries, immutability, and practical use cases for organizing data. Namedtuples provide an efficient and readable way to handle small, immutable data structures, making them an excellent choice for many programming scenarios.

Namedtuples:

Namedtuples are immutable, just like regular tuples, and provide quick and easy ways to define data structures with named fields.

Example 1: Creating a Namedtuple

This example shows how to create a namedtuple and access its fields by name.

Code:

from collections import namedtuple

# Define a namedtuple 'Person' with fields 'name', 'age', and 'city'
Person = namedtuple('Person', ['name', 'age', 'city'])

# Create an instance of Person
svetlana = Person(name='Svetlana Pellam', age=30, city='New York')

# Print the namedtuple
print(svetlana)  # Output: Person(name='John Doe', age=30, city='New York')

# Access fields by name
print(svetlana.name)   
print(svetlana.age)    
print(svetlana.city)  

Output:

Person(name='Svetlana Pellam', age=30, city='New York')
Svetlana Pellam
30
New York

Explanation:

Namedtuples are created using the 'namedtuple()' factory function from the collections module. You define a namedtuple type (e.g., 'Person') with specific fields ('name', 'age', 'city'). Instances of the namedtuple can then be created, and fields can be accessed by name, enhancing code readability.

Using Namedtuple with Default Values:

Python 'namedtuples' can be extended to include default values for fields by using the 'defaults' parameter.

Example 2: Namedtuple with Default Values

This example demonstrates how to set default values for namedtuples.

Code:

from collections import namedtuple
# Define a namedtuple 'Person' with default values for age and city
Person = namedtuple('Person', ['name', 'age', 'city'])
Person.__new__.__defaults__ = (25, 'Unknown')  # Set default age to 25 and city to 'Unknown'
# Create instances of Person with and without default values
silvia = Person(name='Silvia Jayanthi', age=30, city='New York')
enid = Person(name='Enid Deianira')

# Print the namedtuples
print(silvia)   
print(enid)  

Output:

Person(name='Silvia Jayanthi', age=30, city='New York')
Person(name='Enid Deianira', age=25, city='Unknown')

Explanation:

Namedtuples allow setting default values for fields by modifying the '__new__.__defaults__' attribute. In this example, age defaults to 25 and 'city' defaults to 'Unknown' if not specified. This feature is useful for defining default behaviors or values when not all data is available.

Accessing Fields by Index and Using Namedtuple as a Regular Tuple:

'Namedtuples' can be accessed by both field names and index positions, similar to regular tuples.

Example 3: Accessing Namedtuple Fields by Index

This example shows how to access fields of a namedtuple by index and use it like a regular tuple.

Code:

from collections import namedtuple

# Define a namedtuple 'Car' with fields 'make', 'model', and 'year'
Car = namedtuple('Car', ['make', 'model', 'year'])

# Create an instance of Car
car = Car(make='Toyota', model='Corolla', year=2020)

# Access fields by index
print(car[0])  
print(car[1])   
print(car[2])   
# Namedtuples support tuple unpacking
make, model, year = car
print(make, model, year)

Output:

Toyota
Corolla
2020
Toyota Corolla 2020

Explanation:

Namedtuples retain all characteristics of regular tuples, including indexing and unpacking. Fields can be accessed using indices ('car[0]'), or through unpacking ('make, model, year = car'). This dual functionality makes namedtuples versatile and easy to integrate with existing code.

Converting Namedtuple to Dictionary:

'Namedtuples' can be converted into dictionaries using the '_asdict()' method, making it easy to serialize or work with other formats like JSON.

Example 4: Converting Namedtuple to Dictionary

This example demonstrates converting a namedtuple to a dictionary.

Code:

from collections import namedtuple

# Define a namedtuple 'Book' with fields 'title', 'author', and 'year'
Book = namedtuple('Book', ['title', 'author', 'year'])

# Create an instance of Book
book = Book(title='An Introduction to Python', author='Guido van Rossum', year=2024)

# Convert namedtuple to a dictionary
book_dict = book._asdict()

# Print the dictionary
print(book_dict)

Output:

{'title': 'An Introduction to Python', 'author': 'Guido van Rossum', 'year': 2024}

Explanation:

The '_asdict()' method provides a way to convert namedtuples into dictionaries, which is useful for serialization, JSON conversion, or integrating with other data formats. This method enhances the flexibility of namedtuples when interacting with data structures requiring dictionary formats.

Replacing Values in Namedtuples:

Since namedtuples are immutable, we cannot change values directly. However, we can create modified copies using the '_replace()' method.

Example 5: Replacing Values in Namedtuple

This example shows how to create a modified copy of a namedtuple using the _replace() method.

Code:

from collections import namedtuple

# Define a namedtuple 'Employee' with fields 'name', 'position', and 'salary'
Employee = namedtuple('Employee', ['name', 'position', 'salary'])

# Create an instance of Employee
emp = Employee(name='Gisilfrid Ju', position='Developer', salary=80000)

# Create a new instance with an updated salary using _replace()
emp_updated = emp._replace(salary=75000)

# Print the original and updated namedtuples
print(emp)          
print(emp_updated) 

Output:

Employee(name='Gisilfrid Ju', position='Developer', salary=80000)
Employee(name='Gisilfrid Ju', position='Developer', salary=75000)

Explanation:

The '_replace()' method allows you to create a new instance of a namedtuple with one or more fields updated, without modifying the original instance. This method is useful when you need to update fields while preserving the immutability of namedtuples.

Use-Case: Organizing Data with Namedtuples

Namedtuples are excellent for organizing and managing data, especially when readability and lightweight data structures are required.

Example 6: Organizing Student Records

This example shows how namedtuples can be used to organize and manage collections of data, such as student records.

Code:

from collections import namedtuple

# Define a namedtuple 'Student' with fields 'id', 'name', 'grade'
Student = namedtuple('Student', ['id', 'name', 'grade'])

# Create a list of student records
students = [
    Student(id=1, name='Manius Augusto', grade='A'),
    Student(id=2, name='Selma Savitri', grade='B'),
    Student(id=3, name='Emilia Tovi', grade='A')
]

# Print all student records
for student in students:
    print(f"ID: {student.id}, Name: {student.name}, Grade: {student.grade}")

Output:

ID: 1, Name: Manius Augusto, Grade: A
ID: 2, Name: Selma Savitri, Grade: B
ID: 3, Name: Emilia Tovi, Grade: A

Explanation:

Namedtuples provide a readable and structured way to store and access data. In this case, the Student namedtuple makes it easy to work with 'student' records, offering clear access to each field by name, and maintaining the lightweight and performance benefits of tuples.

Comparing Namedtuples

Namedtuples can be compared like regular tuples, allowing for easy sorting and comparison of data structures.

Example 7: Sorting Namedtuples

This example demonstrates sorting namedtuples based on a specific field.

Code:

from collections import namedtuple

# Define a namedtuple 'City' with fields 'name', 'population'
City = namedtuple('City', ['name', 'population'])

# Create a list of cities
cities = [
    City(name='New York', population=8419000),
    City(name='Los Angeles', population=3980000),
    City(name='Chicago', population=2716000)
]

# Sort cities by population in ascending order
sorted_cities = sorted(cities, key=lambda city: city.population)

# Print sorted cities
for city in sorted_cities:
    print(f"City: {city.name}, Population: {city.population}")

Output:

City: Chicago, Population: 2716000
City: Los Angeles, Population: 3980000
City: New York, Population: 8419000

Explanation:

Namedtuples support natural tuple comparison, which allows for sorting and ordering operations. By using a lambda function as a key, you can sort namedtuples by any of their fields. In this case, cities are sorted by population, illustrating the flexibility of namedtuples in handling organized data.



Become a Patron!

Follow us on Facebook and Twitter for latest update.