Using namedtuples field names for column indices in a list of lists

Deborah Swanson python at deborahswanson.net
Mon Jan 9 02:11:58 EST 2017


Steven D'Aprano wrote, on January 08, 2017 7:30 PM
> 
> On Sunday 08 January 2017 20:53, Deborah Swanson wrote:
> 
> > Steven D'Aprano wrote, on January 07, 2017 10:43 PM
> 
> No, I'm pretty sure that's not the case. I don't have access 
> to your CSV file, 
> but I can simulate it:
> 
> ls = [['Location', 'Date', 'Price'],
>       ['here', '1/1/17', '1234'],
>       ['there', '1/1/17', '5678'],
>       ['everywhere', '1/1/17', '9821']
>       ]
> 
> from collections import namedtuple
> lst = namedtuple('lst', ls[0])
> 
> print(type(lst))
> print(lst)
> 
> 
> 
> If you run that code, you should see:
> 
> <class 'type'>
> <class '__main__.lst'>
> 
> 
> which contradicts your statement:
> 
>     'lst' is a namedtuple instance with each of the column 
>     titles as field names.

Yes, yes. In a careless moment I called a class an instance.

> and explains why you had to access the individual property 
> method `fget`: you 
> were accessing the *class object* rather than an actual named 
> tuple instance.

That code is deleted and long gone now, so I can't look at it in the
debugger, but yes, I'm pretty sure 'fget' is a class member.

> The code you gave was:
> 
>     lst.Location.fget(l)
> 
> where l was not given, but I can guess it was a row of the 
> CSV file, i.e. an 
> individual record. So:
> 
> - lst was the named tuple class, a subclass of tuple
> 
> - lst.Location returns a property object
> 
> - lst.Location.fget is the internal fget method of the 
> property object.

And your point is?  Perhaps I didn't express myself in a way that you
could recognize, but I understood all of that before I wrote to you, and
attempted to convey that understanding to you. Obviously I failed, if
you now think I need a lesson in what's going on here.

> I think Peter Otten has the right idea: create a list of 
> records with something 
> like this:
> 
> 
> Record = namedtuple('Record', ls[0])
> data = [Record(*row) for row in ls[1:])
> 
> 
> or if you prefer Peter's version:
> 
> data = [Record._make(row) for row in ls[1:])
> 
> 
> Half the battle is coming up with the right data structures :-)

Can't and wouldn't disagree with any part of that!

> -- 
> Steven
> "Ever since I learned about confirmation bias, I've been seeing 
> it everywhere." - Jon Ronson




More information about the Python-list mailing list