rekeson21
rekeson21

Reputation: 199

How to pass a dictionary as a parameter and then unpack it as variables in the function using it?

I'm trying to pass some parameters to a function and I'm thinking of the best way of doing it. Since there's 32 variables that I want to pass, I wouldn't like to do it manually such as

def myfunction(var1,var2,var3...etc)

so basically what I have is something like this:

def variables():
  dict = {var1:'value1', var2:'value2', var3:'value3'...var32:'value32'}
  return dict

def myfunction(*args):
  print(args)

def main():
  variables_in_dict = variables()
  myfunction(variables_in_dict)

print(args) returns the variable names as in

('var1','var2','var3'....'var32')

My desired output will be something where I could do print(var1) and get value1, as in already having the dictionary keys as variables and the values assigned to those variables.

I'd appreciate any help on this.

Upvotes: 1

Views: 1184

Answers (2)

Lohith
Lohith

Reputation: 934

Using ** instead of *

def variables():
    dictVal = {'var1': 'value1', 'var2': 'value2', 'var3': 'value3'}
    return dictVal


def myfunction(**kwargs):
    print(kwargs['var1'])


variables_in_dict = variables()
myfunction(**variables_in_dict)

Upvotes: 0

ghchoi
ghchoi

Reputation: 5156

If you want to print(var1), how about this:

def myfunction(var1, var2, var3, **kwargs):
    print(var1)

def main():
    variables_in_dict = variables()
    myfunction(**variables_in_dict)

If the super set of parameter names is fixed, you can do the following. If some of them can be omitted, you can assign them default values.

def myfunction(var1, var2, var3, ..., var32):

Also, usually not recommended but as another possibility, you can use exec.

def myfunction(**kwargs):
    for kwarg in kwargs:
        exec("{} = '{}'".format(kwarg, kwargs[kwarg]), globals())
    print(var1)
    print(var2)

This programmatically generates string code to interpret, e.g., "var1 = 'value1'", then execute it. So var1 is programmatically declared and initialized.

Upvotes: 1

Related Questions