Yes. Assuming you want your undict() function in a module:
[code=Python]# module unDict
def unDict(dd, dd0):
for key, value in dd.items():
exec "%s = %s" % (key, repr(value)) in dd0[/code]
Pass the globals() dictionary to the function:[code=Python]import unDict
dd = {'A': 'A string', 'B': 123.456, 'C': [1,2,3,4,5,6], 'D': 456}
unDict.unDict(d d, globals())
print A, B, C, D[/code]Output:
>>> A string 123.456 [1, 2, 3, 4, 5, 6] 456
Is there any other alternative to do this instead of using exec. I am hearing the use of exec is not a good practice as it is a dowside factor for performance?
Is there any other alternative to do this instead of using exec. I am hearing the use of exec is not a good practice as it is a dowside factor for performance?
Thanks in Advance
SKN
[code=Python]globals().updat e(dd)[/code]The keys in dictionary dd are now available as variable names.
I suppose, if I use with in a method/function, then I can use locals.update(d d) instead of globals().updat e(dd).
Please correct me if I am wrong.
SKN
You cannot update the local dictionary - it's not allowed. It can be done by passing the global dictionary to the function for updating.
[code=Python]>>> dd = {'a': 1, 'b': 2}
>>> a
Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
NameError: name 'a' is not defined
>>> def update_dict(dd_ to_update, dd):
... dd_to_update.up date(dd)
...
>>> update_dict(glo bals(), dd)
>>> a
1
>>> [/code]
You cannot update the local dictionary - it's not allowed. It can be done by passing the global dictionary to the function for updating.
[code=Python]>>> dd = {'a': 1, 'b': 2}
>>> a
Traceback (most recent call last):
File "<interacti ve input>", line 1, in ?
NameError: name 'a' is not defined
>>> def update_dict(dd_ to_update, dd):
... dd_to_update.up date(dd)
...
>>> update_dict(glo bals(), dd)
>>> a
1
>>> [/code]
If I use globals().updat e(dd) then the variables become global. I would like it to keep it local.
If I use globals().updat e(dd) then the variables become global. I would like it to keep it local.
It could be encapsulated in a module. The global namespace for a function is always the module in which it was defined.[code=Python]>>> import amodule
>>> amodule.update_ dict(amodule.up date_dict.func_ globals, {'value1': 10.5, 'value2': 127.6})
>>> amodule.value1
10.5
>>> [/code]
Comment