_replace method of namedtuple class from the collections module in Python

Method Name:

_replace

Method Signature:

_replace(**kwargs)

Parameters:

kwargs - keyword arguments corresponding to one or more fields whose values to be modified.

Return Value:

Updated named tuple with the replaced values.

Overview:

  • The _replace() method updates an existing value of a field with a new value and returns a new named tuple.

Example:

# Example Python program that replaces the values of one or more

# fields on a named tuple object to create a new tuple

import collections

import csv

 

# Create a named tuple type for tax scheme

schedule = collections.namedtuple("schedule", "event, date, location");

 

s1 = schedule("Design discussions", "10/12/2020", "Conf room-1");

s2 = schedule("Test case review", "11/12/2020", "Conf room-2");

 

print("Original Schedule:");

print(s1);

print(s2);

 

us1 = s1._replace(date = "9/12/2020");

us2 = s2._replace(date = "10/12/2020");

 

print("Updated Schedule:");

print(us1);

print(us2);

 

 

Output:

Original Schedule:

schedule(event='Design discussions', date='10/12/2020', location='Conf room-1')

schedule(event='Test case review', date='11/12/2020', location='Conf room-2')

Updated Schedule:

schedule(event='Design discussions', date='9/12/2020', location='Conf room-1')

schedule(event='Test case review', date='10/12/2020', location='Conf room-2')

 

 


Copyright 2024 © pythontic.com