You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将Python嵌套字典二级键改为首字母大写其余小写格式

问题原因

你写的代码存在两处核心问题:

  1. 语法错误:字典推导式的书写格式错误,自定义的首字母判断逻辑也不成立
  2. 逻辑错误:循环中直接给dict1整体赋值,会直接覆盖整个外层字典,最终只会保留最后一个学科的数据,丢失其他内容

实现方法

Python字符串内置的capitalize()方法刚好可以满足「首字母大写、其余字母小写」的需求,不需要自行写判断逻辑,实现代码如下:

方案1:直接修改原字典

for subject in dict1:
    dict1[subject] = {name.capitalize(): score for name, score in dict1[subject].items()}

方案2:生成新字典不改动原数据

new_dict = {
    subject: {name.capitalize(): score for name, score in score_dict.items()}
    for subject, score_dict in dict1.items()
}

运行结果

处理后最终的字典结构为:

{
    'math': {'John': 7, 'Lisa': 4, 'Karyn': 3},
    'eng': {'Lisa': 5, 'Toby': 4, 'Karyn': 11, 'Ryan': 3},
    'phy': {'Karyn': 7, 'John': 7, 'Steve': 9, 'Joe': 9}
}

内容的提问来源于stack exchange,提问作者newbzzs

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.01 19:18:01