如何在python中将字典项作为函数参数传递?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21986194/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 00:01:59  来源:igfitidea点击:

How to pass dictionary items as function arguments in python?

pythonfunctionpython-2.7dictionary

提问by Patrick

My code

我的代码

1st file:

第一个文件:

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

2nd file:

第二个文件:

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

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(),但我想要键值对传递。如何纠正这个?

I want the my_function()to get modified like this

我希望my_function()像这样修改

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

and this is my requirement, give answers according to this

这是我的要求,根据这个给出答案

EDIT:dictionary key classis changed to standard

编辑:字典键更改为标准

采纳答案by RemcoGerlich

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 callthe function:

现在您可以**调用函数时使用:

data = {'school':'DAV', 'standard': '7', 'name': 'abc', 'city': 'delhi'}

my_function(**data)

and it will work as you want.

它会按你的意愿工作。

P.S.Don't use reserved words such as class.(e.g., use klassinstead)

PS不要使用保留字,例如class.(例如,klass改为使用)

回答by Jakob Bowyer

You can just pass it

你可以通过它

def my_function(my_data):
    my_data["schoolname"] = "something"
    print my_data

or if you really want to

或者如果你真的想

def my_function(**kwargs):
    kwargs["schoolname"] = "something"
    print kwargs

回答by venpa

*data interprets arguments as tuples, instead you have to pass **data which interprets the arguments as dictionary.

*data 将参数解释为元组,而您必须传递 **data 将参数解释为字典。

data = {'school':'DAV', 'class': '7', 'name': 'abc', 'city': 'pune'}


def my_function(**data):
    schoolname  = data['school']
    cityname = data['city']
    standard = data['class']
    studentname = data['name']

You can call the function like this:

你可以这样调用函数:

my_function(**data)