0

This question is similar to the one asked here:

However in my case I have a large dictionary filled with many keys and values, and I will not be able to enumerate each key to implement this solution:

from operator import itemgetter

params = {'a': 1, 'b': 2}
a, b = itemgetter('a', 'b')(params)

In my case:

from operator import itemgetter

params = {'a': 1, 'b': 2 ........... 'y': 25, 'z': 26 }

a, b ..... y, z = itemgetter('a', 'b'.... 'y', 'z')(params)

Is there any way I can unpack and assign each key to it's value, and associate values with variables names after its keys on a large scale?

Please Advise.

# Function
a = 1
b = 2

def foo(z):
 return a + b + z

foo(3)

# should return 6
The Singularity
  • 2,428
  • 3
  • 19
  • 48
  • 1
    Why do yo need them in dynamically named variables? You already have them in a `dict` so you have access to them by name... – user2390182 Aug 25 '21 at 09:30
  • I'm trying to unpack and define them to pass them as additional arguments for a function that can only take one argument – The Singularity Aug 25 '21 at 09:33
  • What type is that argument supposed to be, a tuple or list? or you want to pass them one by one to repeated calls to said function? – user2390182 Aug 25 '21 at 09:37
  • the question you linked is very old (11 years), dicts are "ordered" now. you probably don't need the itemgetter stuff. the reason why you want to ditch the dict is still unclear – diggusbickus Aug 25 '21 at 11:03
  • @diggusbickus I want to unpack a dictionary, define those global variables (values to keys), and run a function using those global variables – The Singularity Aug 25 '21 at 11:06
  • 1
    Here's the [actual issue](https://stackoverflow.com/questions/53845951/pyspark-multiple-parameters-for-pandas-udf-grouped-agg) I'm trying to solve with this question – The Singularity Aug 25 '21 at 11:07
  • 2
    maybe you should ask for help on that problem because i think you're on the wrong way – diggusbickus Aug 25 '21 at 11:33

1 Answers1

0

Either state the variables as input argument and unpack the dictionary in the call

def foo(z, a, b):
    return a + b + z 

param = {'a': 1, 'b': 2}

foo(3, **param)
>> 6

then you could also provide default values (for example 0) if any input should be missing.

Another possibility is to provide provide the entire dictionary as input and let the function handle the unpacking.

def bar(z, p):
     return p['a'] + p['b'] + z 

bar(3, param)
>> 6
NLindros
  • 1,683
  • 15
  • 15