Home > Back-end >  Python Map or Filter function with variable assignment
Python Map or Filter function with variable assignment

Time:05-22

Is there a way to use either of the map or filter functions to map a list of variables to a function and assign a variable (the name of the variable) to each of those outputs?

    mapping_tables = ['Assets_Table','Liabilities_Table','Equity_Table','Income_Table']

I have a list of tables that I'm applying to a function which will convert it into a dataframe and then assign a variable to the dataframe from the list of mapping_tables. At the moment the following 'for loop' works.

for table_name in mapping_tables:
    globals()[table_name] = load_data_table_to_df(sheet_name, table_name)

Is there a way to optimize this? Perhaps using one of the Map or Filter functions? or even a different python library? Or is this as simple as it gets?

Thank you

CodePudding user response:

If you really want to use map():

# Assuming `sheet_name` is defined somewhere...
def table_to_df(table_name):
    return table_name, load_data_to_df(sheet_name, table_name)


frames = dict(map(table_to_df, mapping_tables))

Then when you want to work on one of your dataframes:

frames[table_name]
  • Related