pir
pir

Reputation: 5933

Replacing value of variable in list of named tuples

I'm loading data about phone calls into a list of namedtuples called 'records'. Each phone call has information on the length of the call in the variable 'call_duration'. However, some have the variable set to None. I would like to replace None with zero in all of the records, but the following code doesn't seem to work:

for r in records:
        if r.call_duration is None:
            r = r._replace(call_duration=0)

How can replace the value in the list? I guess the problem is that the new 'r' isn't stored in the list. What would be the best way to capture in the change in the list?

Upvotes: 2

Views: 228

Answers (2)

Malik Brahimi
Malik Brahimi

Reputation: 16721

I suggest you create your own class, it will benefit you in the future as far as object management goes. When you want to create methods later on for a record, you'll be able to easily do so in a class:

class Record:
    def __init__(self, number = None, length = None):
        self.number = number
        self.length = length

    def replace(self, **kwargs):
        self.__dict__.update(kwargs)

Now you can easily manage your records and replace object attributes as you deem necessary.

for r in records:
    if r.length is None:
        r.replace(length = 0)

Upvotes: 0

PM 2Ring
PM 2Ring

Reputation: 55499

You can replace the old record by using its index in the records list. You can get that index using enumerate():

for i, rec in enumerate(records):
    if rec.call_duration is None:
        records[i] = rec._replace(call_duration=0)

Upvotes: 2

Related Questions