将字典传递给python中的函数作为关键字参数 [英] Passing a dictionary to a function in python as keyword parameters

查看:784
本文介绍了将字典传递给python中的函数作为关键字参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



这是一些代码:



我想使用一个字典在python中调用一个函数。 pre> d = dict(param ='test')

def f(param):
打印参数

f d)

这将打印 {'param':'test'} 但是我想要打印 test



我想要对于更多参数,可以同样工作:

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

是这可能吗?

解决方案

结束了自己的想法。很简单,我只是错过了**操作符来解压缩字典



所以我的例子变成:

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


I'd like to call a function in python using a dictionary.

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.

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)

这篇关于将字典传递给python中的函数作为关键字参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆