如何在python中传递字典项作为函数参数? [英] How to pass dictionary items as function arguments in python?

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

问题描述

我的代码

第一个文件:

data = {'school':'DAV', 'standard': '7', 'name': 'abc', 'city': 'delhi'}
my_function(*data)

第二个文件:

my_function(*data):
    schoolname  = school
    cityname = city
    standard = standard
    studentname = name

在上面的代码中,只有数据字典的键被传递给 my_function(),但是我想要键值对通过。如何纠正这个?

in the above code, only keys of "data" dictionary were get passed to my_function(), but i want key-value pairs to pass. How to correct this ?

我希望 my_function()像这样修改

my_function(school='DAV', standard='7', name='abc', city='delhi')

这是我的要求,根据这个提供答案

and this is my requirement, give answers according to this

<编辑:字典键更改为标准

推荐答案

如果要像这样使用它们,可以使用变量名称定义函数(但是使用 klass class ,你不能使用保留字):

If you want to use them like that, define the function with the variable names as normal (but use klass for class, you can't use reserved words):

def my_function(school, city, klass, name):
    schoolname  = school
    cityname = city
    standard = klass
    studentname = name

现在(只要您的字典中的类重新命名为klass),当您呼叫时,您可以使用 ** 功能:

Now (as long as you rename class to klass in your dictionary) you can use ** when you call the function:

my_function(**data)

,它可以按需要工作。

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

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