[Tutor] A CSV field is a list of integers - how to read it as such?
Dave Angel
davea at davea.name
Thu Mar 7 04:33:39 CET 2013
On 03/06/2013 09:05 PM, DoanVietTrungAtGmail wrote:
>> Once a csv file has been read by a csv reader (such as DictReader), it's
>> no longer a csv file.
>
>
> That was an "Aha!" moment for me. The file is on disk, each row of it is in
> memory as a list or dict, and it's the list or dict that matters. It's so
> obvious now. Thanks Dave.
>
>>
>
> a namedtuple is probably exactly what you want.
>
>
> I read this as meaning that while tuples themselves are immutable, to
> effectively modify it I simply delete it and replace it with a new tuple
> with new values. Another 'Aha!'
>
A collections.namedtuple is not the same as a tuple. The items in it
can be addressed either by index, or by name. But each instance of the
tuple does *not* waste space duplicating those names. The names are
stored once per type of namedtuple
http://docs.python.org/2/library/collections.html#collections.namedtuple
Look at the example following the comment:
""" Named tuples are especially useful for assigning field names to
result tuples returned by the csv or sqlite3 modules:"
And an instance created through collections.namedtuple has a useful method:
somenamedtuple._replace(kwargs)
Return a new instance of the named tuple replacing specified fields with
new values:
--
DaveA
More information about the Tutor
mailing list