Python列表内嵌字典引发KeyError:读取'name'键失败求助
解决KeyError: 'name'错误
你的代码运行时触发KeyError: 'name',核心原因是maximum_volume函数往l_report里添加的字典仅包含max_volume键,没有name键,但最后遍历l_report时直接访问每个字典的name键,因此触发报错。
错误代码片段
def maximum_volume(): global dict_report list_volume = [] #LIST CONTAINING CURRENCY VOLUMES for elements in currencies: list_volume.append(elements['quote']['USD']['volume_24h']) for elements in currencies: if max(list_volume) == elements['quote']['USD']['volume_24h']: dict_report ={ 'max_volume' : elements['name'] } l_report.append(dict_report)
修复方案
推荐统一l_report内字典的结构,这样后续逻辑更易维护,以下是两种可行方案:
方案1:统一字典结构(添加name键)
修改maximum_volume的字典定义,让它和top10生成的字典结构一致:
def maximum_volume(): global dict_report list_volume = [] #LIST CONTAINING CURRENCY VOLUMES for elements in currencies: list_volume.append(elements['quote']['USD']['volume_24h']) max_val = max(list_volume) # 提前计算最大值,避免重复遍历 for elements in currencies: if max_val == elements['quote']['USD']['volume_24h']: dict_report ={ 'name' : elements['name'], 'max_volume' : max_val # 按需存储volume值,也可保留原结构只加name键 } l_report.append(dict_report)
方案2:兼容两种字典结构(修改遍历逻辑)
如果不想改动maximum_volume的输出结构,遍历的时候可以先判断键是否存在:
for k in l_report: print(k.get('name', k.get('max_volume'))) # 有name键取name,没有则取max_volume对应的值
额外优化建议
你代码里maximum_volume两次遍历currencies的逻辑可以合并,提升效率:
def maximum_volume(): global dict_report max_volume = -float('inf') max_currency_name = "" for elements in currencies: current_volume = elements['quote']['USD']['volume_24h'] if current_volume > max_volume: max_volume = current_volume max_currency_name = elements['name'] dict_report ={ 'name' : max_currency_name, 'max_volume' : max_volume } l_report.append(dict_report)
内容的提问来源于stack exchange,提问作者klok
相关产品推荐
相关产品推荐

