python - 参数不兼容时字典解包为函数

标签 python dictionary

我不确定这是否可行,我想将字典解包到函数中,但我没有类似的参数。是否可以轻松地将字典限制为一个子集?

def foo(a=0, b=0, c=0):
    print("a=%s, b=%s, c=%s"%(a,b,c))

my_dict = {'a':10, 'b':20, 'd':40}
foo(**my_dict)

输出

TypeError                                 Traceback (most recent call last)
<ipython-input-1-d40731664736> in <module>()
      3 
      4 my_dict = {'a':10, 'b':20, 'd':40}
----> 5 foo(**my_dict)

TypeError: foo() got an unexpected keyword argument 'd'

我想得到

a=10, b=20, c=0

'd' 被自动拒绝的结果。

这只是一个例子。在我的例子中,函数不是我的,我不能重新定义她的参数,foo 是不可修改的。

在与 foo() 类似的情况下,我有许多函数,这些函数是对象的方法。

有什么想法吗?

最佳答案

Inspecting the function signature将帮助:

import inspect

params = inspect.signature(foo).parameters.keys()

foo(**{k: v for k, v in my_dict.items() if k in params})

关于python - 参数不兼容时字典解包为函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47715035/

相关文章:

Python lxml(对象化): Xpath troubles

vb.net - 字典访问 : composite key vs concatenated string index

python - 为字典设置元素 getter

Python 循环遍历字典列表以查找属性

python - 无法外部连接两个数据框

python - KNN 模型返回与任意 k 相同的距离

python - 在Python3中为DataFrame创建列名的问题

python - 为什么不能绑定(bind)到 0.0.0.0 :80 and 192. 168.1.1 :80 simultaneously?

c++ - 发现元素何时插入到 std::map

python - 有什么优雅的方法可以在 python 中构建多级字典吗?