0

I'm having a problem with my python code, I'm running a function but that function requires some arguments and the number of arguments I give is different every time, this number is going to depend on how big my array is, I thought about a for loop but it doesn't work inside the function.

data['x'] = 1
data['z'] = 2
somefunction(for y in data: data_y=data[y])
Tomas Alves
  • 60
  • 1
  • 10
  • Just to pass dict as argument you could do `somefunction(*data)` – Filip Młynarski Nov 17 '18 at 18:34
  • 1
    Your question is unclear. If you want a function that has `x` and `z` as arguments because you have `'x'` and `'z'` as keys in your `data` dictionary, then [use `**kwargs`](http://book.pythontips.com/en/latest/args_and_kwargs.html#usage-of-kwargs). If you want a function that has a variable number of arguments, but you only care about the order and not the names, then [use `*args`](http://book.pythontips.com/en/latest/args_and_kwargs.html#usage-of-args). – Marco Bonelli Nov 17 '18 at 18:37

2 Answers2

3

* should do the trick. See this for more on the topic.

The *args will give you all function parameters as a tuple:

def somefunction(*args):
  for x in args:
    print(x * 10)

Test it:

data = ['a', 'b', 'c']

somefunction(data[0], data[1], data[2])

Output:

aaaaaaaaaa
bbbbbbbbbb
cccccccccc

Use ** for key word arguments:

The **kwargs will give you all keyword arguments except for those corresponding to a formal parameter as a dictionary

def somefunction(**kwargs):
  for key in kwargs:
    print(key, "->", kwargs[key])

Test it:

data = ['a', 'b', 'c']

somefunction(y1 = data[0], y2 = data[1], y3 = data[2])

Output:

y1 -> a
y2 -> b
y3 -> c
Aykhan Hagverdili
  • 28,141
  • 6
  • 41
  • 93
0

I see that you try to pass argument that is a dict and answers here point to function with array type argument, so here's example code that shows how to do that with dict.

def somefunction(**kwargs):
    for arg in kwargs:
        print(arg, kwargs[arg])

data = {'x': 1, 'z': 2}
somefunction(**data)
# z 2
# x 1
data = {'x': 1, 'y':2, 'z': 3}
somefunction(**data)
# z 3
# x 1
# y 2
Filip Młynarski
  • 3,534
  • 1
  • 10
  • 22