"unpacking" a passed dictionary into the function's name space in Python? "unpacking" a passed dictionary into the function's name space in Python? python python

"unpacking" a passed dictionary into the function's name space in Python?


You can always pass a dictionary as an argument to a function. For instance,

dict = {'a':1, 'b':2}def myFunc(a=0, b=0, c=0):    print(a,b,c)myFunc(**dict)


If you like d.variable syntax better than d['variable'], you can wrap the dictionary in an almost trivial "bunch" object such as this:

class Bunch:    def __init__(self, **kw):        self.__dict__.update(kw)

It doesn't exactly bring dictionary contents into the local namespace, but comes close if you use short names for the objects.


Assuming all keys in your dictionary qualify to be identifiers,You can simply do this:

adict = { 'x' : 'I am x', 'y' : ' I am y' }for key in  adict.keys():  exec(key + " = adict['" + key + "']")blah(x)blah(y)