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]]
  • Does this answer your question? [Does Python have a ternary conditional operator?](https://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator) – YUVI_1303 Oct 17 '22 at 11:13
  • @YUVI_1303 kind of but how do i deal with the key error? thats why i was thinking of a try and catch but how does that account for if one of them is not filled? – f33lthepkfromprins Oct 17 '22 at 11:16
  • 1
    Does this answer your question? [Check if a given key already exists in a dictionary](https://stackoverflow.com/questions/1602934/check-if-a-given-key-already-exists-in-a-dictionary) – Luuk Oct 17 '22 at 11:27

2 Answers2

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]
Anis R.
  • 6,656
  • 2
  • 15
  • 37
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)]
Peter
  • 3,186
  • 3
  • 26
  • 59