1

I've seen this question a few times before, and invariably I see that people always respond by saying that this is a bad idea. What is a good way to approach this issue? I have a code that reads in data from several csv files in a for loop, i.e for each loop iteration a different csv is read. At the end of my for loop, I make a dictionary with some data in it. All I would like to do is name this dictionary after the original csv file's name.

At the moment I have:

sessionname=str(inputList).replace(".csv",'').replace("'",'').replace("[",'').replace("]",'')
session_dict={}

What I would like is for session_dict to be named using the string in sessionname. Therefore at the end of my for loop, I would have a number of dictionaries each with the name of its orginal csv file.

Thank you!

Vikram
  • 33
  • 6
  • 2
    Have you tried nested dictionaries instead? – bigbounty Jul 05 '20 at 10:20
  • Hi, So my session_dict dictionary is actually nested already. I fear it might start getting too complicated? Additionally, the csv files correspond to data from different people so in my head independent dictionaries work better? – Vikram Jul 05 '20 at 10:22
  • If it's getting too complicated then create a different dictionary for different purposes – bigbounty Jul 05 '20 at 10:23
  • Thats exactly my thought process, so at the moment I have a nested dictionary session_dict with all the relevant information I need from one csv file. However, I just wish to name then in a way that I can easily differentiate one dictionary from another since they are generated from the for loop. – Vikram Jul 05 '20 at 10:27
  • You can name the nested dictionaries i.e keys as the file names as you have done in your code – bigbounty Jul 05 '20 at 10:28
  • What are you trying to achieve by this? If the name of the csv is well-known (e.g. hardcoded), you can already manually name the variable the same. If the name of the csv is not well-known (e.g. found via ``glob``), the rest of the code also does not know the name and cannot access the dynamically named variable. Why don't you use a *dictionary* mapping from the csv name to the session_dict? – MisterMiyagi Jul 05 '20 at 10:29
  • bigbounty and MisterMiyagi, you are both correct and have clarified the issue for me! Yes, I can just name the keys after the string. I am not sure why this did not occur to me, but thank you very much! – Vikram Jul 05 '20 at 10:32

1 Answers1

0

You can't create a variable named after a filepath, because of the slashes and the spaces, etc. One thing you can do is to name each of your dictionaries with a number (or a unique code), and in run-time create a reference dictionary like:

ref_dict = {r'csv_file_0_path' :0, r'csv_file_1_path': 1, r'csv_file_2_path': 2} 

and so on.

Fab
  • 142
  • 8