Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic way to sorting list of namedtuples by field name

I want to sort a list of named tuples without having to remember the index of the fieldname. My solution seems rather awkward and was hoping someone would have a more elegant solution.

from operator import itemgetter from collections import namedtuple  Person = namedtuple('Person', 'name age score') seq = [     Person(name='nick', age=23, score=100),     Person(name='bob', age=25, score=200), ]  # sort list by name print(sorted(seq, key=itemgetter(Person._fields.index('name')))) # sort list by age print(sorted(seq, key=itemgetter(Person._fields.index('age')))) 

Thanks, Nick

like image 253
Nick Avatar asked Aug 23 '12 08:08

Nick


People also ask

How do you sort a list of lines in Python?

The easiest way to accomplish this task is to call Python's built-in sorted() function that takes an iterable and returns a new list with sorted elements. The sorted() function generates a new sorted list that is put into the print() function that prints the sorted list to the shell.

Can we sort a part of the list in Python?

Based on the results of the key function, you can sort the given list. Here, len is Python's in-built function to count the length of an element. The list is sorted based on the length of each element, from lowest count to highest. We know that a tuple is sorted using its first parameter by default.

Can NamedTuple have methods?

count() and . index() , namedtuple classes also provide three additional methods and two attributes. To prevent name conflicts with custom fields, the names of these attributes and methods start with an underscore. In this section, you'll learn about these methods and attributes and how they work.


2 Answers

from operator import attrgetter from collections import namedtuple  Person = namedtuple('Person', 'name age score') seq = [Person(name='nick', age=23, score=100),        Person(name='bob', age=25, score=200)] 

Sort list by name

sorted(seq, key=attrgetter('name')) 

Sort list by age

sorted(seq, key=attrgetter('age')) 
like image 185
jamylak Avatar answered Sep 20 '22 01:09

jamylak


sorted(seq, key=lambda x: x.name) sorted(seq, key=lambda x: x.age) 
like image 21
clyfish Avatar answered Sep 22 '22 01:09

clyfish