Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Copying named tuples with same attributes / fields

I am writing a function that takes a named tuple and must return a super set of that tuple.

For example if I was to receive a named tuple like this:

Person(name='Bob', age=30, gender='male')

I want to return a tuple that looks like this:

Person(name='Bob', age=30, gender='male', x=0)

Currently I am doing this:

tuple_fields = other_tuple[0]._fields
tuple_fields = tuple_fields + ('x')
new_tuple = namedtuple('new_tuple', tuple_fields)

Which is fine, but I do not want to have to copy each field like this:

tuple = new_tuple(name=other_tuple.name, 
                  age=other_tuple.age, 
                  gender=other_tuple.gender, 
                  x=0)

I would like to be able to just iterate through each object in the FIRST object and copy those over. My actual tuple is 30 fields.

like image 391
Brian Crafton Avatar asked Dec 05 '16 18:12

Brian Crafton


Video Answer


1 Answers

You could try utilizing dict unpacking to make it shorter, eg:

tuple = new_tuple(x=0, **other_tuple._asdict())
like image 174
user3030010 Avatar answered Sep 27 '22 18:09

user3030010