1

I would like to iteratively convert a dictionary into matching global variables like shown below:

# starting dictionary
parameters = {
    'a': 3,
    'b': 4
}

# result
a = 3
b = 4

now I know quite well the caveats associated with global variables: this is not meant to be a "production" solution but rather a way to use the considerable existing code base for optimization purposes without implementing a heavy restructuring.

any ideas?

Asher11
  • 1,295
  • 2
  • 15
  • 31

2 Answers2

3

You can use locals:

locals().update({'test': 2})

Results:

>>test
>>2
hamza tuna
  • 1,467
  • 1
  • 12
  • 17
1
# starting dictionary
parameters = {
    'a': 3,
    'b': 4
}

locals().update(parameters)
print(a)
print(b)

OUTPUT:

3
4

OR

a, b = parameters['a'], parameters['b']

OR

Consider the Bunch alternative::

class Bunch(object):
    def __init__(self, parameters):
        self.__dict__.update(parameters)

parameters = {
    'a': 3,
    'b': 4
}
vars = Bunch(parameters)
print(vars.a, vars.b)

OUTPUT:

3 4
DirtyBit
  • 16,613
  • 4
  • 34
  • 55