Skip to content Skip to sidebar Skip to footer

Python: How Can I Use An Enumerate Element As A String?

I have a list of dict1.keys() I'm enumerating over and I'd like to use the element as a string. for i,j in enumerate(dict1.keys()): str(j) = somethingElse >>> SyntaxError

Solution 1:

Because you are generating your pandas dataframe dynamically inside a for loop so at the end when you print j it will show you the last generated dataframe. You should store your dataframe in list Try using this:

listOfFrame = [] 
for j in dict.keys(): 
    j = pd.DataFrame(dict[j]['Values'])
    listOfFrame.append(j)

Solution 2:

Indeed j will be a str (or whatever else type of key you are using in dict).

The actual problem is with the loop body, as the error message states:

str(j) = somethingElse

is not valid Python. The left hand side is a call to the str function, so you cannot assign a value to it.


Solution 3:

Based on the comments you want neither enumerate nor to iterate over the dict keys. Instead, you want to iterate over its values:

dfs = []
for val in dict1.values():
    dfs.append(pd.DataFrame(val['Values']))

However, this would normally written without an explicit loop in Python, for instance by using list comprehension:

dfs = [pd.DataFrame(val['Values']) for val in dict1.values()]

Solution 4:

From the question linked below, elements are able to be used as a key in a dict. After reducing the question to "use list item as name for dataframe" and searching that, it verks. I'll post as an answer also:

dict2={}
for i in dict1: dict2[i] = pd.DataFrame(dict1[i]['Values'])

..thus the names are preserved. Actually, this is similar to Sheri's answer with lists, but the names retain association with the dfs. There may not be a way to set a variable value using something other than a plain string, but I'll start a different question for that.

use elements in a list for dataframe names


Post a Comment for "Python: How Can I Use An Enumerate Element As A String?"