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

如何对Dict.py文件中的字典调用invert_dict函数实现反转?

正确实现方法

首先明确问题核心:open()返回的是文件对象,不是字典类型,直接传给invert_dict函数自然会报错,必须先把Dict.py里的Dictionary字典加载到内存中再处理。

方法一:直接导入字典(最简洁推荐)

假设Dict.py的内容是:

# Dict.py
Dictionary = {"name": "Alice", "age": 25, "city": "New York"}

在你的主脚本中直接导入这个字典,再调用反转函数:

# 主脚本代码
from Dict import Dictionary

def invert_dict(target_dict):
    # 处理值唯一的情况,若值重复可改用列表存储(见下方补充)
    return {value: key for key, value in target_dict.items()}

# 执行反转并输出
result = invert_dict(Dictionary)
print(result)

方法二:读取文件并解析(不推荐,仅作场景补充)

如果必须通过文件读取的方式获取字典,可通过exec解析文件内容提取变量:

def invert_dict(target_dict):
    return {value: key for key, value in target_dict.items()}

# 读取并解析Dict.py
with open("Dict.py", "r", encoding="utf-8") as f:
    file_content = f.read()
    exec(file_content)  # 执行文件内容,将Dictionary加载到当前环境
    result = invert_dict(Dictionary)
    print(result)

补充:处理值重复的字典反转

如果原字典存在重复值,直接反转会导致键被覆盖,可修改函数将值存储为列表:

def invert_dict(target_dict):
    inverted = {}
    for key, value in target_dict.items():
        inverted.setdefault(value, []).append(key)
    return inverted

# 示例:原字典有重复值
test_dict = {"a": 1, "b": 2, "c": 1}
print(invert_dict(test_dict))  # 输出 {1: ['a', 'c'], 2: ['b']}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 14:55:21