-1

I want to read multiple csv files using pandas library and I want to assign that dataframe to items in the list using for loop. Currently I have two lists (One list contains dataframe names and second list contains dataframe) I am using below code for example:

list1 = ['amol', 'ankit', 'akshay', 'ashok'] # in actual there are 100+ items in the list
marks = [50, 60, 70, 80]   # marks list actully contains dataframe - pandas.core.frame.DataFrame

for ind, name in enumerate(list1):
    name = marks[ind]
print(amol)

# NameError: name 'amol' is not defined.

This is not assigning value to 'amol' and giving "NameError: name 'amol' is not defined."

I tried using dictionary.

list1 = ['amol', 'ankit', 'akshay', 'ashok']
marks = [50, 60, 70, 80]

mark_dict = {}

for ind, name in enumerate(list1):
    mark_dict[name] = marks[ind] 
print(mark_dict['amol'])

Dictionary is working but I want to assign value to 'amol' so below code can be executed and shold give me a output (in actual project it should return dataframe). Please advice how can I do it?

print(amol) 

pgg08927
  • 145
  • 10

1 Answers1

0

You can add variables to the module's global namespace using globals(). zip will turn the two lists into an itertator of matching tuples (list1[0], marks[0]) etc... globals().update works like a regular dict.update so these tuples can be fed into it directly to update the namespace.

list1 = ['amol', 'ankit', 'akshay', 'ashok'] # in actual there are 100+ items in the list
marks = [50, 60, 70, 80]

globals().update(zip(list1, marks))
print(amol)

This is not a common thing to do. Normally one would keep dynamically generated data like this in a dictionary.

tdelaney
  • 73,364
  • 6
  • 83
  • 116
  • I want to read multiple csv files using pandas library and I want to assign that dataframe to 'amol' using for loop. so when I print amol it should print dataframe. – pgg08927 Jul 29 '20 at 16:32