Dictionary keys-items to objects in python

Viewed 44

Many times I make a data checkpoint on my code, so I start from there next day without running the code again. I do that by saving the python objects into a dictionary and then to pickle. e.g.

saved_dict = { 'A' : 'a', 'B' : ['b'], 'C' : 3} etc

And when I load it i do:

A = saved_dict['A']

B = saved_dict['B'] ... etc

I wonder if there is a way to do that in an automated way, maybe with a for loop, instead of writing them all one by one.

Any ideas ?

2 Answers

You can assign directly to globals(), without the need of exec, which could be a source of security issues.

>>> saved_dict = { 'A' : 'a', 'B' : ['b'], 'C' : 3}
>>> for k,v in saved_dict.items():
...     globals()[k] = v
... 
>>> A
'a'
>>> B
['b']
>>> C
3

Note that this is a terrible idea and there are definetly better solutions for your problem itself (for example not storing a dict). But I shall entertain this:

for k in saved_dict:
   exec(f"{k} = {saved_dict[k]}")

Note that you need exec and not eval, as assignments are not expressions. This is an attrocity and im going to hell for this crime.

Related