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

Steve D'Aprano steve+python at pearwood.info
Mon Jan 9 06:39:45 EST 2017


On Mon, 9 Jan 2017 09:57 pm, Deborah Swanson wrote:

[...]
> I think you are replying to my question about sorting a namedtuple, in
> this case it's called 'records'.
> 
> I think your suggestion works for lists and tuples, and probably
> dictionaries. But namedtuples doesn't have a sort function.

Tuples in general (whether named or not) represent structs or records, where
the position of the item is significant. It doesn't usually make sense to
sort individual elements of a record or tuple:

Before sorting: Record(name='George', spouse='', position='Accountant')
After sorting:  Record(name='', spouse='Accountant', position='George')


I think what you want to do is sort a list of records, not each record
itself. Or possibly you want to reorder the columns, in which case the
easiest way to do that is by editing the CSV file in LibreOffice or Excel
or another spreadsheet application.

If you have a list of records, call .sort() on the list, not the individual
records. 

But if I am wrong, and you absolutely must sort the fields of each record,
call the sorted() function, which will copy the fields into a list and sort
the list. That is:

alist = sorted(record)





-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list