How to pass dictionary items as function arguments in python?

Patrick picture Patrick · Feb 24, 2014 · Viewed 200.4k times · Source

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 ?

I want the my_function() to get modified like this

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

and this is my requirement, give answers according to this

EDIT: dictionary key class is changed to standard

Answer

RemcoGerlich picture RemcoGerlich · Feb 24, 2014

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)

and it will work as you want.

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