In a different question I tried to use an enumerate and for element to create a pandas dataframe using the element as the name. It turns out the problem is more general. Is there anyway to set a variable value using something other than a plain string? In Bash this is done with the Read command, which takes the previous output into a subshell and assigns it to a variable name (I'll post my question on that below).
Any way to do this in Python? i.e., something simple like:
list1[0] = pd.dataframe(data)
, where list1[0] is a string. Or similarly using a dict key where the value is a dataframe:
for i in dict1: i = dict1[key]
or for i in dict1: function(i) = dict1[key]
?
The latter doesn't work using str() or any function because the error complains "SyntaxError: can't assign to function call", but maybe something similar?
Python: How can I use an enumerate element as a string?
https://unix.stackexchange.com/questions/338000/bash-assign-output-of-pipe-to-a-variable
EDIT:
Okay, well, after extended discussion with @juanpa.arrivillaga, he explained that strings are not plain strings as in Bash. Let's see if I have this right.. they are string objects stored in dict objects. (even integers are stored as objects unless using numpy or pandas which expand on Python arrays). Inside a for i in dict1:
loop print(i) works because 'print will call str implicitly on any object you pass to it'. i = value does not because 'think of variables as nametags you throw on objects' and i is being resolved in its for loop scope as a dict object key. I'm not sure why, but variable 'nametags' cannot be string objects.
A workaround using globals() kind of mentioned in the Duplicate answers exists:
for key in dict1: globals()[key] = pd.DataFrame()
This is because in CPython, they used actual python objects to implement the global namespaces. It might be possible to 'maybe use ctypes to modify the namespace array in a local scope', as another workaround is to use SimpleNamespace to create a new object to store variables (presumably because they are stored as objects, the same as in globals(). And to wrap up, 'setattr(sys.modules[_name_], var_name, var_value)
is equivalent to globals()[var_name] = var_value
'.