Python基于字典与输入值生成输出时出现KeyError报错的问题问询
问题分析与解决:字典KeyError错误
问题背景
需求:输入tipe_kelas为private时返回100000,结合字典生成对应输出。
提供的Python代码:
list_harga = {'private':100000,'group':50000} list_harga name = str(input('nama: ')) member = str(input('member: ')) tipe_kelas = str(input('kelas: ')) harga=[list_harga[x] for x in tipe_kelas] harga
运行时触发错误:
KeyError Traceback (most recent call last) ~\AppData\Local\Temp\ipykernel_15824\2571049863.py in <module> 8 print(tipe_kelas) 9 ---> 10 harga=[list_harga[x] for x in tipe_kelas] 11 harga ~\AppData\Local\Temp\ipykernel_15824\2571049863.py in <listcomp>(.0) 8 print(tipe_kelas) 9 ---> 10 harga=[list_harga[x] for x in tipe_kelas] 11 harga KeyError: 'g'
问题根源
错误出在这行代码:harga=[list_harga[x] for x in tipe_kelas]
- Python中遍历字符串时,会逐个取出每个字符。比如输入的
tipe_kelas是group,遍历后会得到'g'、'r'、'o'、'u'、'p'这几个单个字符 - 但字典
list_harga的键是完整的'private'和'group',没有单个字符的键,所以当代码尝试用'g'去字典里找对应值时,自然找不到,触发KeyError。
修正方案
不需要用列表推导式遍历输入的字符串,直接用完整的tipe_kelas作为键去字典取值即可:
list_harga = {'private':100000,'group':50000} name = input('nama: ') member = input('member: ') tipe_kelas = input('kelas: ') # 直接用输入的班级类型作为键取值 harga = list_harga[tipe_kelas] print(harga)
如果要避免用户输入不存在的班级类型导致报错,可以用字典的get()方法设置默认提示:
harga = list_harga.get(tipe_kelas, "输入的班级类型不存在") print(harga)
内容的提问来源于stack exchange,提问作者Amelia Putri Damayanti
相关产品推荐
相关产品推荐

