Home > front end >  How do I loop through a dictionary, and apply a function using key: value pairs as arguments
How do I loop through a dictionary, and apply a function using key: value pairs as arguments

Time:11-25

Dictionary = {File1: "location1", File2: "location2", File3: "location3"}

def fancy_function1(location, file):        
  df = pd.read_csv(location)
  df["new_column"] = df[file]
return df 

need help needed writing this for loop or any other suggestions

for key in Dictionary:
   ##pass key value pairs into function
    df = fancy_function(key, value)
    return df

I want to then merge all 3 dataframes (created from fancy_function()) or assign each dataframe to variables e.g. df1, df2, df3 etc.

CodePudding user response:

I don't know if this helps.

for key in Dictionary:
    value = Dictionary[key]
    df = fancy_function(key, value)
    return df

For me this is strange because you are returning outside a function, if you want to create multiple data frames I suggest the following.

dataframes = []
for key in Dictionary:
    value = Dictionary[key]
    df = fancy_function(key, value)
    dataframes.append(df)

The append method appends to a list so you have a list with all your data frames, be careful because this can consume a lot of ram if you have a lot of data frames or some are big. I hope this helps.

CodePudding user response:

for key in Dictionary:
##pass key value pairs into function
    if df in locals():
        df = fancy_function(key, value)
    else
        df=pd.concat([df, fancy_function(key, value)])
    return df
  • Related