Python生成感染与检测结果列表时的KeyError问题求助
问题解决:字典取值避免KeyError+处理空字典场景
需求说明
需要生成两个列表:
infectedDetected:存储results里infected和detection子字典中True对应的值,没有True键时用0填充notinfectedDetected:存储results里infected和detection子字典中False对应的值,已知False键几乎总是存在,若不存在(比如子字典为空)也用0填充
原代码及问题
用户原代码运行时会触发KeyError,因为直接通过键索引取值,当子字典里没有True键时就报错:
results = {'infected': {False: 39}, 'detection': {False: 39}} infectedDetected = [results['infected'][True], results['detection'][True]] notinfectedDetected = [results['infected'][False], results['detection'][False]]
用户错误尝试
用户尝试的一行式判断写法逻辑错误,无法捕获KeyError:
infectedDetected = [results['infected'][True] if not Keyerror else 0, results['detection'][True] if results['detection'][True] != KeyError else 0] notinfectedDetected = [results['infected'][False], results['detection'][False]]
期望输出示例
infectedDetected = [0, 0] notinfectedDetected = [39, 39]
正确解决方案
用字典的get()方法,它可以指定键不存在时的默认值,同时能处理子字典为空的情况:
results = {'infected': {False: 39}, 'detection': {False: 39}} # 处理True对应的取值,不存在则返回0 infectedDetected = [ results['infected'].get(True, 0), results['detection'].get(True, 0) ] # 处理False对应的取值,已知几乎存在,保险起见也用get,不存在则返回0 notinfectedDetected = [ results['infected'].get(False, 0), results['detection'].get(False, 0) ] print(f"infectedDetected = {infectedDetected}") print(f"notinfectedDetected = {notinfectedDetected}")
代码说明
dict.get(key, default):如果字典里存在key,返回对应值;不存在则返回default指定的值- 即使
infected或detection是个空字典{},get()也会返回默认值0,完美覆盖空字典场景
内容的提问来源于stack exchange,提问作者f33lthepkfromprins
相关产品推荐
相关产品推荐

