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

如何将字典名称作为函数参数传入?TypeError错误求助

问题:如何通过输入字典名称将字典传入带**参数的函数?

原代码

data = {'employer':'Apppe, Inc', 'title': 'Senior Software Engineer', 'manager': 'Steve Jobs', 'city': 'Cupertino'}


def my_function(**data):
    employername  = data['employer']
    title = data['title']
    manager = data['manager']
    city = data['city']
    print(city)
    

my_function(**data)
username = input("Enter dictionary name:")
my_function(**username)

报错信息

Enter dictionary name:data
Traceback (most recent call last):
  File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 31, in <module>
    start(fakepyfile,mainpyfile)
  File "/data/user/0/ru.iiec.pydroid3/files/accomp_files/iiec_run/iiec_run.py", line 30, in start
    exec(open(mainpyfile).read(),  __main__.__dict__)
  File "<string>", line 14, in <module>
TypeError: __main__.my_function() argument after ** must be a mapping, not str

[Program finished]

原因分析

input()函数返回的是字符串类型,而**操作符要求后面必须是字典这类映射(mapping)对象,直接把字符串传给**就会触发类型错误。

解决方案

要通过输入的变量名获取对应的字典对象,可以借助globals()函数——它返回当前全局作用域的变量字典,键是变量名,值是对应的变量对象。同时建议增加判断逻辑,避免输入不存在的变量名导致报错。

修改后的代码如下:

data = {'employer':'Apppe, Inc', 'title': 'Senior Software Engineer', 'manager': 'Steve Jobs', 'city': 'Cupertino'}


def my_function(**data):
    employername  = data['employer']
    title = data['title']
    manager = data['manager']
    city = data['city']
    print(city)
    

my_function(**data)
dict_name = input("Enter dictionary name:")
# 从全局作用域获取对应的字典对象
target_dict = globals().get(dict_name)
if isinstance(target_dict, dict):
    my_function(**target_dict)
else:
    print(f"Error: '{dict_name}' is not a valid dictionary in current scope")

补充说明

  • 如果字典是定义在局部作用域(比如某个函数内部),可以用locals()替代globals()来获取局部变量字典。
  • 直接用globals()[dict_name]也能取到变量,但如果输入的变量名不存在会触发KeyError,用get()更安全,返回None可以做后续判断。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 20:10:50