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

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

问题描述

我想使用字典在python中调用一个函数.

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

这是一些代码:

d = dict(param='test')

def f(param):
    print(param)

f(d)

这将打印{'param': 'test'},但我希望它仅打印test.

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)

这可能吗?

推荐答案

最后自己解决了这个问题.很简单,我只是缺少**操作符来解开字典

Figured it out for myself in the end. It is simple, I was just missing the ** operator to unpack the dictionary

所以我的示例变为:

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

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

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