简体   繁体   English

将字典作为关键字参数传递给函数

[英]Passing a dictionary to a function as keyword parameters

I'd like to call a function in python using a dictionary.我想使用字典在 python 中调用一个函数。

Here is some code:这是一些代码:

d = dict(param='test')

def f(param):
    print(param)

f(d)

This prints {'param': 'test'} but I'd like it to just print test .这会打印{'param': 'test'}但我希望它只打印test

I'd like it to work similarly for more parameters:我希望它对更多参数有类似的工作:

d = dict(p1=1, p2=2)
def f2(p1, p2):
    print(p1, p2)
f2(d)

Is this possible?这可能吗?

Figured it out for myself in the end.最后自己想通了。 It is simple, I was just missing the ** operator to unpack the dictionary很简单,我只是缺少 ** 运算符来解包字典

So my example becomes:所以我的例子变成了:

d = dict(p1=1, p2=2)
def f2(p1,p2):
    print p1, p2
f2(**d)
In[1]: def myfunc(a=1, b=2):
In[2]:    print(a, b)

In[3]: mydict = {'a': 100, 'b': 200}

In[4]: myfunc(**mydict)
100 200

A few extra details that might be helpful to know (questions I had after reading this and went and tested):一些可能有助于了解的额外细节(我在阅读本文并进行测试后遇到的问题):

  1. The function can have parameters that are not included in the dictionary该函数可以具有字典中包含的参数
  2. You can not override a function parameter that is already in the dictionary不能覆盖字典中已经存在的函数参数
  3. The dictionary can not have values that aren't in the function.字典不能包含不在函数中的值。

Examples:例子:

Number 1: The function can have parameters that are not included in the dictionary数字 1:函数可以有字典中没有的参数

In[5]: mydict = {'a': 100}
In[6]: myfunc(**mydict)
100 2

Number 2: You can not override a function parameter that is already in the dictionary数字 2:您不能覆盖字典中已经存在的函数参数

In[7]: mydict = {'a': 100, 'b': 200}
In[8]: myfunc(a=3, **mydict)

TypeError: myfunc() got multiple values for keyword argument 'a'

Number 3: The dictionary can not have values that aren't in the function.数字 3:字典不能包含不在函数中的值。

In[9]:  mydict = {'a': 100, 'b': 200, 'c': 300}
In[10]: myfunc(**mydict)

TypeError: myfunc() got an unexpected keyword argument 'c'

How to use a dictionary with more keys than function arguments:如何使用键多于函数参数的字典:

A solution to #3, above, is to accept (and ignore) additional kwargs in your function (note, by convention _ is a variable name used for something being discarded, though technically it's just a valid variable name to Python):上面 #3 的解决方案是在你的函数中接受(并忽略)额外的 kwargs(注意,按照约定_是用于被丢弃的东西的变量名,尽管从技术上讲它只是 Python 的有效变量名):

In[11]: def myfunc2(a=None, **_):
In[12]:    print(a)

In[13]: mydict = {'a': 100, 'b': 200, 'c': 300}

In[14]: myfunc2(**mydict)
100

Another option is to filter the dictionary based on the keyword arguments available in the function:另一种选择是根据函数中可用的关键字参数过滤字典:

In[15]: import inspect
In[16]: mydict = {'a': 100, 'b': 200, 'c': 300}
In[17]: filtered_mydict = {k: v for k, v in mydict.items() if k in [p.name for p in inspect.signature(myfunc).parameters.values()]}
In[18]: myfunc(**filtered_mydict)
100 200

Example with both positional and keyword arguments:具有位置和关键字参数的示例:

Notice further than you can use positional arguments and lists or tuples in effectively the same way as kwargs, here's a more advanced example incorporating both positional and keyword args:请注意,您可以像使用 kwargs 一样有效地使用位置参数和列表或元组,这是一个结合位置参数和关键字参数的更高级示例:

In[19]: def myfunc3(a, *posargs, b=2, **kwargs):
In[20]:    print(a, b)
In[21]:    print(posargs)
In[22]:    print(kwargs)

In[23]: mylist = [10, 20, 30]
In[24]: mydict = {'b': 200, 'c': 300}

In[25]: myfunc3(*mylist, **mydict)
10 200
(20, 30)
{'c': 300}

In python, this is called "unpacking", and you can find a bit about it in the tutorial .在 python 中,这称为“解包”,您可以在教程中找到一些相关信息。 The documentation of it sucks, I agree, especially because of how fantasically useful it is.我同意它的文档很烂,尤其是因为它非常有用。

Here ya go - works just any other iterable:在这里你去 - 适用于任何其他可迭代:

d = {'param' : 'test'}

def f(dictionary):
    for key in dictionary:
        print key

f(d)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM