Home > OS >  Python if ... else on one line
Python if ... else on one line

Time:10-17

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]]

CodePudding user response:

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]

CodePudding user response:

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)]
  • Related