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

如何让Python代码实现完整字典反转而非仅输出部分内容

问题根因
  • 循环缩进错误:遍历角色的第二层for循环没有放在第一层遍历学院的循环内部,第一层循环执行结束后,变量val仅保留了最后一个学院的角色列表,最终只处理了这一组数据,所以输出只有拉文克劳学院的内容。
  • append方法使用错误:列表append()方法为原地修改操作,返回值为None,直接将append()结果赋值给字典值,后续如果出现同个角色属于多个学院的场景,会抛出属性异常。
修正后代码
# Character Reference Dictionary
Harry_Potter_Characters = {
    'Gryfindor': ["Harry Potter", 'Hermione Granger', 'Ron Weassley', 'Neville Longbottom'],
    'Hufflepuff': ["Nymphadora Tonks", 'Newton Scamnder', 'Helga Hufflepuff', 'Cedric Diggory'],
    'Slytherine': ["Leta Lastrange", 'Albus Potter', 'Regulas Black', 'Tom Riddle'],
    'Ravenclaw': ["Luna Lovegood", 'Filius Flitwick', 'Sybill Trelawney', 'Myrtle Warren']
}

print('Harry Potter Character Roster and House Dictionary', Harry_Potter_Characters)
print("")

# Modified inverse dictionary function
def invert_dict(d):
    inverse = dict()
    for key in d:
        val = d[key]
        # 缩进调整:第二层循环放在第一层内部,处理每个学院的所有角色
        for sub_key in val:
            if sub_key not in inverse:
                inverse[sub_key] = [key]
            else:
                # 去掉赋值,直接调用append即可
                inverse[sub_key].append(key)
    return inverse

print('Inverted dictionary:', invert_dict(Harry_Potter_Characters))

修正后即可输出所有角色对应所属学院的完整反转字典。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 06:45:04