Shani de Leeuw Shani de Leeuw - 4 months ago 19
Python Question

Sorting a list of named tuples by field numercially

I'm fairly new to using python. I have a list of namedtuples which I would like to sort numerically by one of the fields. I currently have code that looks something like this:

from collections import namedtuple

testTuple = namedtuple("test", "name, number")
from operator import itemgetter

testList = []
seq = [testTuple(name = 'abc', number = '123'),
testTuple(name = 'xyz', number = '32'),
testTuple(name = 'def', number = '322')]
print(sorted(seq, key= itemgetter(1)))


But of course since itemgetter sorts alphabetically the tuple associated with 123 is printed before that associated with 32. I'm unsure if I can somehow combine key=itemgetter(x) with key=int to solve my issue.

Answer

I think that writing a small lambda function is best you'll be able to do:

from collections import namedtuple

testTuple = namedtuple("test", ("name", "number"))

seq = [testTuple(name = 'abc', number = '123'),
       testTuple(name = 'xyz', number = '32'),
       testTuple(name = 'def', number = '322')]

print(sorted(seq, key=lambda x: int(x[1])))

# Output:
# [test(name='xyz', number='32'), test(name='abc', number='123'), test(name='def', number='322')]