处理 Python 中的 KeyError

Handle KeyError in Python

我如何处理 KeyError 的 if's?根据错误,从不同的方式处理错误。

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

我想要的是,如果键 team_normal 不存在于字典中,则将我选择的值分配给该键。

但是当键team_normal存在时,只需要给键值赋值即可。

应该这样做:

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

只需检查密钥是否存在:

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

如果只有最后一个key可以不存在,可以用get:

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

如果你想挂起任何键错误,你应该使用 try 块:

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