如何在python中将字典项作为函数参数传递? [英] How to pass dictionary items as function arguments in python?
本文介绍了如何在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
字典键 class 更改为 standard
dictionary key class is changed to standard
推荐答案
如果你想像这样使用它们,请像往常一样用变量名定义函数:
If you want to use them like that, define the function with the variable names as normal:
def my_function(school, standard, city, name):
schoolName = school
cityName = city
standardName = standard
studentName = name
现在您可以在调用函数时使用**
:
Now you can use **
when you call the function:
data = {'school':'DAV', 'standard': '7', 'name': 'abc', 'city': 'delhi'}
my_function(**data)
它会如你所愿.
P.S. 不要使用保留字,例如 class
.(例如,使用 klass
代替)
P.S. Don't use reserved words such as class
.(e.g., use klass
instead)
这篇关于如何在python中将字典项作为函数参数传递?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文