Home > Mobile >  Handle KeyError in Python
Handle KeyError in Python

Time:10-19

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.

CodePudding user response:

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!")

CodePudding user response:

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

CodePudding user response:

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

CodePudding user response:

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