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

如何编写接收固定键值+任意关键字参数的Python函数?

Python字典存储函数作业问题解答

你的问题核心遗漏点

  • 未将key1、key2与关键字参数合并为完整的目标字典,仅打印了零散参数
  • 没有维护历史存储的字典(即要求的{'key1': 'other1', 'key2': 'other2'}),无法输出历史数据
  • 函数未返回生成的字典,不满足add = yourfunc(...)的赋值调用要求
  • 误用内置类型名dict作为函数名,会覆盖系统原生的dict类型,属于不规范写法

修正后的代码示例

方案1:使用全局变量维护历史(适合入门课程理解)

# 预先存储要求的历史字典
previous_dict = {'key1': 'other1', 'key2': 'other2'}

def yourfunc(key1, key2, **extra):
    # 合并必填参数与关键字参数为当前字典
    current_dict = {'key1': key1, 'key2': key2}
    current_dict.update(extra)
    
    # 输出要求的内容
    print("当前生成的字典:", current_dict)
    print("之前存储的字典:", previous_dict)
    
    # 返回当前字典,支持赋值操作
    return current_dict

# 测试调用
add = yourfunc('value1', 'value2', key3='value3', key4='value4')

方案2:使用闭包维护状态(更优雅的无全局变量写法)

如果课程涉及闭包概念,也可以用这种方式避免全局变量:

def create_dict_manager():
    # 闭包内部维护历史字典,外部无法直接修改
    previous_dict = {'key1': 'other1', 'key2': 'other2'}
    
    def yourfunc(key1, key2, **extra):
        nonlocal previous_dict
        current_dict = {'key1': key1, 'key2': key2}
        current_dict.update(extra)
        
        print("当前生成的字典:", current_dict)
        print("之前存储的字典:", previous_dict)
        
        # 可选:如果需要每次调用后更新历史字典,取消下面注释
        # previous_dict = current_dict.copy()
        
        return current_dict
    
    return yourfunc

# 创建函数实例
yourfunc = create_dict_manager()
# 测试调用
add = yourfunc('value1', 'value2', key3='value3', key4='value4')

代码说明

  • 函数严格遵循要求:接收必填的key1、key2,支持任意数量的关键字参数
  • 合并所有参数生成目标字典,并返回它以满足add = ...的赋值需求
  • 输出包含当前生成的字典和预先存储的历史字典,完全符合作业要求
  • 避免了覆盖内置类型名的问题,函数名改为yourfunc(可根据需求修改)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 22:42:56