0

So im trying to get 2 lists with the infected and detected. results (almost always) contains False and could contain True. im getting a keyerror with this code. Maybe a try..catch but what if either infection or detection is empty?

results = {'infected': {False: 39}, 'detection': {False: 39}}
    
infectedDetected = [results['infected'][True],
                    results['detection'][True]]

notinfectedDetected = [results['infected'][False],
                       results['detection'][False]]

Example of the preferred output:

infectedDetected = [0, 0]
notinfectedDetected = [39, 39]

What i've tried:

infectedDetected = [results['infected'][True] if not Keyerror else 0,
                    results['detection'][True] if results['detection'][True] != KeyError else 0]

notinfectedDetected = [results['infected'][False],
                       results['detection'][False]]
3

2 Answers 2

1

To solve the KeyError, you can check if the dict contains the desired key like so:

if True in results['infected']

So the ternary operator in your case can look like:

infectedDetected = [results['infected'][True] if True in results['infected'] else 0,
                results['detection'][True] if True in results['detection'] else 0]
Sign up to request clarification or add additional context in comments.

Comments

1

I presume you can manage with try/except KeyError, but this is an alternative way where you can use the default value of .get().

infectedDetected = [results.get('infected', {}).get(True, 0),
                    results.get('detection', {}).get(True, 0)]

notinfectedDetected = [results.get('infected', {}).get(False, 0),
                       results.get('detection', {}).get(False, 0)]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.