自定义Alexa技能Python Lambda匹配预设名称触发KeyError问题咨询
报错根因
KeyError: 'daddy'完全是字典键大小写不匹配导致的:
- 你定义的
Player_BIOGRAPHY所有键都是首字母大写格式(比如"Daddy"、"John"),根本没有全小写的"daddy"键 - 取值时代码写的是
Player_BIOGRAPHY[name.lower()],强行把输入转成全小写去匹配字典,自然找不到对应键 - 未命中预设列表时走的是else分支,不会访问这个字典,所以那部分流程正常,只有命中列表的场景会触发错误
修复方案
方案1:直接统一字典键为全小写(最省事,适配现有判断逻辑)
把原Player_BIOGRAPHY定义改成全小写键:
Player_BIOGRAPHY = { "john": "peeee-you, Jasper smells like a stinky pair of week old socks that have been left out in the rain", "horatio": "Ughhhh, Horatio smells just like an elephant's bum that has been sweltering in the desert for a month", "mummy": "Mummy smells beautiful, like the scent of freshly cut roses or sweet perfume", "daddy": "Oh wow, the worst. He smells like a combination of burnt popcorn and rotting fish combined with sewer water and stinky armpits" }
方案2:保留原字典格式,新增大小写映射层(不用改动原有文案)
在Player_BIOGRAPHY定义完成后加一行转换代码:
# 生成全小写键的映射,规避大小写匹配问题 BIO_LOWER_MAP = {k.lower(): v for k, v in Player_BIOGRAPHY.items()}
再把player_bio函数里的取值行改成:
return output_json_builder_with_reprompt_and_card(BIO_LOWER_MAP[name.lower()], card_TEXT, card_TITLE, reprompt_MSG, False)
方案3:容错取值(适合不想改动原有字典的场景)
如果要保留原字典的首字母大写键格式,直接把输入转成首字母大写再匹配即可:
把player_bio函数里的取值行改成:
return output_json_builder_with_reprompt_and_card(Player_BIOGRAPHY[name.capitalize()], card_TEXT, card_TITLE, reprompt_MSG, False)
内容的提问来源于stack exchange,提问作者crashoveride
相关产品推荐
相关产品推荐

