Best way to optimize this code so it takes up less space?
There is indeed a great deal of repetition in your code. A straight-forward solution to this would be putting your severity levels into a dictionary and iterate over it instead:
test = {
    &quot;version&quot;: &quot;0&quot;,
    &quot;id&quot;: &quot;85fc3613-e913-7fc4-a80c-a3753e4aa9ae&quot;,
    &quot;detail-type&quot;: &quot;ECR Image Scan&quot;,
    &quot;source&quot;: &quot;aws.ecr&quot;,
    &quot;account&quot;:
        &quot;123456789012&quot;,
    &quot;time&quot;: &quot;2019-10-29T02:36:48Z&quot;,
    &quot;region&quot;: &quot;us-east-1&quot;,
    &quot;resources&quot;: [
        &quot;arn:aws:ecr:us-east-1:123456789012:repository/my-repo&quot;
    ],
    &quot;detail&quot;: {
        &quot;scan-status&quot;: &quot;COMPLETE&quot;,
        &quot;repository-name&quot;: &quot;my-repo&quot;,
        &quot;finding-severity-counts&quot;: {
            &quot;CRITICAL&quot;: 10,
            &quot;MEDIUM&quot;: 9
        }
    }
}

resource = test[&quot;resources&quot;][0]
finding_severity_counts = test[&quot;detail&quot;][&quot;finding-severity-counts&quot;]

THRESHOLDS = {
    'CRITICAL' : 0,
    'MEDIUM'   : 1,
    'LOW'      : 0
}

for severity in THRESHOLDS:
    if severity in finding_severity_counts:
        count = finding_severity_counts[severity]
        if count &gt; THRESHOLDS[severity]:
            print(&quot;Resource {} has {} {} findings&quot;.format(resource, count, severity.lower()))

This should produce the exact same result as your code does, by reusing the logic (that's the same for every severity. Note that we can reuse the count, since we're only interested in one value at a time.
That is, assuming you're only interested in the amount of severities if they reach a certain threshold. Hence the name.
It would probably be prettier to put the for-loop into a function though. An even better solution would probably involve one of Python's 'collections' functions, like Counter.