Iterate through a Python Flask-sqlalchemy Query Result as a list comprehension


I have a flask-sqlalchemy query which returns a list of alert data.

alert_data = Alerts.query.filter_by(alertRemediated = False).all()

I am iterating through the result with the below code to count all "Critical" alerts.

This code works, but seem inefficient.

c = 0
for alert in alert_data:
    if alert.alertSeverity == 'Critical':
        c +=1
total_crit_alerts = c

I’ve tried the following list comprehension to make the code more streamlined, but I cannot get it to work.

total_crit_alerts = sum(1 for i in alert_data.alertSevertiy if i == 'Critical')

The error returned is: AttributeError: 'list' object has no attribute 'alertSevertiy'

Any suggestions would be greatly appreciated.

Asked By: Bryan



You need to iterate through alert_data list.
Also you have type in alertSeverity

You can try:

total_crit_alerts = sum(1 for i in alert_data if i.alertSeverity == 'Critical')
Answered By: Clueless

Here is something that worked for me, hopefully this helps.

# Trying to mock each Alert
from typing import NamedTuple

class Alert(NamedTuple):
    description: str
    alertSeverity: str

# mocking an alert response
alert_data = [
    Alert(f"example alert {idx}", f"Critical" if idx % 2 == 0 else f"Info")
    for idx in range(1, 10)

# counting critical alerts
total_crit_alerts = sum(
    1 if alert.alertSeverity == "Critical" else 0 for alert in alert_data

print(total_crit_alerts) # should be 4

# this should also work
c = 0
for alert in alert_data:
    if alert.alertSeverity == 'Critical':
        c +=1
total_crit_alerts_ = c

print(total_crit_alerts_) # 4

Answered By: Dario
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.