A
A
Andrey Grinevich2015-08-15 18:10:37
Python
Andrey Grinevich, 2015-08-15 18:10:37

How to create a namedtuple with a dynamic number of fields?

Good day
An example from the manual of the collections module:

EmployeeRecord = namedtuple('EmployeeRecord', 'name, age, title, department, paygrade')
import csv
for emp in map(EmployeeRecord._make, csv.reader(open("employees.csv", "rb"))):
    print emp.name, emp.title

In production, such an unpleasant moment surfaced, the number of fields in a document that is imported from Google Doc may change, or requirements have been added or some marks have been added.
Because of this, I have to read csv in the old-fashioned way and access fields by index, which makes me very sad. I'm interested in the first few fields of the csv file and their order will never change.
Is there a way to create a namedtuple with a dynamic number of fields?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Kirill Romanov, 2015-08-15
@Djaler

If I understand the problem correctly stackoverflow.com/questions/15324644/how-do-i-add-...

A
Artem Klimenko, 2015-08-16
@aklim007

If you know in advance what fields will definitely be and you are only interested in them, why not just create your own class with these parameters, __init__ of which will take these parameters as input in the right order, and *args - which will include everything else, which you can if you wish keep or ignore.
if you care about memory allocation use __slots__

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question