-1

I am working on a load function that loads files containing one pandas dataframe per file (or even better one np array). I.e. I am loading a .csv file and I want to link it to only one array variable.

This function takes as input one dictionary containing the name I want (as key) the variable to take and the name+path of the comma separated file (as value).

Here is an example of what an input of this function should look like:

    d = {'XLF' : 'X4_2_LF.csv', 'XHF' : 'X4_2_HF.csv',
        'yLF' : 'y4_4_LF.csv', 'yHF' : 'y4_4_HF.csv'}

With this function I would like to load those 4 files and return as output either the single array variables XLF, XHF, yLF, yHF or a single dictionary (or something like that) containing those variables.

I successfully loaded those files but I don't know how to return them as outputs, given that I could have a variable number of elements in the input dict.

This is what I've come up to:

def load_data_dic(d):
    path = os.getcwd() + '\\results\\data\\'
    out = {}
    for key, val in d.items():
        nm = path + val
        locals()[key] = pd.read_csv(nm, index_col = 0).to_numpy()
    return out #don't know how to fill it!
mz_97
  • 15
  • 5
  • 1
    Does this answer your question? [How can I add new keys to a dictionary?](https://stackoverflow.com/questions/1024847/how-can-i-add-new-keys-to-a-dictionary) – mkrieger1 Aug 28 '22 at 08:09
  • Thank you, I was using locals because at first I wanted to create variables named after the dictionary's keys (that would still be my goal but I'm ok also with the dict created without locals(). – mz_97 Aug 28 '22 at 08:14
  • 1
    Edit: Solved this by calling locals() in the main function instead of using it in the function above – mz_97 Aug 28 '22 at 08:20

1 Answers1

1

Don't mess with locals() unless you're absolutely sure you know what you're doing.

IIUC this is what you need:

def load_data_dic(d):
    path = os.getcwd() + '\\results\\data\\'
    out = {}
    for key, val in d.items():
        nm = path + val
        out[key] = pd.read_csv(nm, index_col = 0).to_numpy()
    return out
DarkKnight
  • 19,739
  • 3
  • 6
  • 22
  • Thank you, as mentioned above I was working with locals because I was trying to unpack the dict in variables named after the key. Seems I was doing it in the wrong place – mz_97 Aug 28 '22 at 08:22