Search code examples
pythondictionaryif-statementkeyerror

Handle KeyError in Python


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.


Solution

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