In Python, what is the easiest way to get the total count of one field from a set of named tuples?
In this example, I'm looking for the total count of TestResults.failed
, which should be 4. It's doable with a for
loop, but it feels like there could be a more efficient way.
from collections import namedtuple
TestResults = namedtuple('TestResults', ['failed', 'attempted'])
test_results = [
TestResults(0, 5),
TestResults(3, 28),
TestResults(1, 7)
]
failed_count = 0
for r in test_results:
if hasattr(r, 'failed'):
failed_count += r.failed
print(failed_count)
With arbitrary objects, you can use getattr
with 0
as a default value, and use sum
with a generator expression:
sum(getattr(res, 'failed', 0) for res in test_results)
Since you have namedtuples with no optional values, you can get the values directly using dot notation:
sum(res.failed for res in test_results)
If you have a namedtuple with an optional 'failed'
field, if the optional value is 0
, then the above should work, otherwise, if the optional value is None
, you could use this to use 0
as a default value:
sum(res.failed or 0 for res in test_results)