1

How can i handle KeyError with if's? Depending the error, handling the error from a diferrent way.

speed_uhc_team = counts_stats['games']['SPEED_UHC']['modes']['team_normal']
speed_uhc_solo = counts_stats['games']['SPEED_UHC']['modes']['solo_normal']

What i want is if the key team_normal don't exist in the dictionary assign a value of my choice to that key.

But when the key team_normal exists, just assign the key value.

3
  • 1
    if 'team_normal' not in counts_stats['games']['SPEED_UHC']['modes'].keys(): Commented Oct 18, 2021 at 11:51
  • i don't understand - you watn to assign a value in both cases. So what's the difference? Commented Oct 18, 2021 at 11:54
  • @Psytho if the value don't exist on the dict assign a value of my choice Commented Oct 18, 2021 at 11:59

4 Answers 4

3

If only the last key can be absent, you can use get:

speed_uhc_team = counts_stats['games']['SPEED_UHC']['modes'].get('team_normal',
                                                                 default_value)

If you want to hangle any key error, you should use a try block:

try:
    speed_uhc_team = counts_stats['games']['SPEED_UHC']['modes']['team_normal']
except KeyError:
    speed_uhc_team = default_value
Sign up to request clarification or add additional context in comments.

Comments

1

Just check if the key is present:

if 'team_normal' not in counts_stats['games']['SPEED_UHC']['modes'].keys():
    speed_uhc_team = my_choice_value
    
else:
    speed_uhc_team = counts_stats['games']['SPEED_UHC']['modes']['team_normal']

Comments

0

This should do it:

d = { "team_solo": True}

if "team_normal" in d:
    print("I found team_normal in d!")

if "team_solo" in d:
    print("I found team_solo in d!")

Comments

0
try:
  speed_uhc_team = counts_stats['games']['SPEED_UHC']['modes']['team_normal']
except KeyError:
  speed_uhc_team = counts_stats['games']['SPEED_UHC']['modes']['other_key']

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.