Python: Create A Variable Using Something Other Than A Plain String?
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 a
Solution 1:
Sorry it's quite hard to understand what exactly the question is.
for i in dict1: function(i) = dict[key]
A couple of problems with this: the thing on the left is what you're assigning, so the syntax should be dict[key] = function(i)
(but don't call your dicts 'dict' because that's a reserved keyword). This is assuming key is defined somewhere. This is why you're getting the error you describe - you cant assign to a function call, you assign to variables.
As for storing things in list, you can put whatever you like in there, same with dictionaries. For example:
import pandas as pd
ls = [pd.DataFrame(), 'Hello']
d = {
'a': pd.DataFrame(),
1: pd.DataFrame()
}
print(ls)
print(d['a'])
print(d[1])
Solution 2:
I think this issue can be solved with dictionaries:
var_names = ['your_string', 'your_second_string']
dict = {}
for i, var_name inenumerate(var_names):
var_name = f'var_name{i}'dict[var_name] = pd.DateFrame([])
Post a Comment for "Python: Create A Variable Using Something Other Than A Plain String?"