I found an easy way to get the dictionary value, and its name as well! I'm not sure yet about reading it back, I'm going to continue to do research and see if I can figure that out.
Here is the code:
your_dict = {'one': 1, 'two': 2}
variables = [var for var in dir() if var[0:2] != "__" and var[-1:-2] != "__"]
file = open("your_file","w")
for var in variables:
if isinstance(locals()[var], dict):
file.write(str(var) + " = " + str(locals()[var]) + "\n")
file.close()
Only problem here is this will output every dictionary in your namespace to the file, maybe you can sort them out by values? locals()[var] == your_dict
for reference.
You can also remove if isinstance(locals()[var], dict):
to output EVERY variable in your namespace, regardless of type.
Your output looks exactly like your decleration your_dict = {'one': 1, 'two': 2}
.
Hopefully this gets you one step closer! I'll make an edit if I can figure out how to read them back into the namespace :)
---EDIT---
Got it! I've added a few variables (and variable types) for proof of concept. Here is what my "testfile.txt" looks like:
string_test = Hello World
integer_test = 42
your_dict = {'one': 1, 'two': 2}
And here is the code the processes it:
import ast
file = open("testfile.txt", "r")
data = file.readlines()
file.close()
for line in data:
var_name, var_val = line.split(" = ")
for possible_num_types in range(3): # Range is the == number of types we will try casting to
try:
var_val = int(var_val)
break
except (TypeError, ValueError):
try:
var_val = ast.literal_eval(var_val)
break
except (TypeError, ValueError, SyntaxError):
var_val = str(var_val).replace("\n","")
break
locals()[var_name] = var_val
print("string_test =", string_test, " : Type =", type(string_test))
print("integer_test =", integer_test, " : Type =", type(integer_test))
print("your_dict =", your_dict, " : Type =", type(your_dict))
This is what that outputs:
string_test = Hello World : Type = <class 'str'>
integer_test = 42 : Type = <class 'int'>
your_dict = {'two': 2, 'one': 1} : Type = <class 'dict'>
I really don't like how the casting here works, the try-except block is bulky and ugly. Even worse, you cannot accept just any type! You have to know what you are expecting to take in. This wouldn't be nearly as bad if you only cared about dictionaries, but I really wanted something a bit more universal.
If anybody knows how to better cast these input vars I would LOVE to hear about it!
Regardless, this should still get you there :D I hope I've helped out!