Search code examples
pythonpandaslistdepth-first-search

Pythonic way to associate list of dataframes to list of strings


In encountered this problem when converting a json object to a csv:

I now have two lists:

list_A is a list of strings. Each string is a name of df.

list_A = ['df1', 'df2', 'df3'] 

list_B has 3 pandas.core.frame.DataFrame objects.

list_B[0] = [an entire df with columns, rows etc]

What code would ensure association between strings from the one list with the dataframes in the other, such as df1 = list_B[0] then df2 = list_B[1] and so on?

Thank you


Solution

  • Either use a dictionary:

    dfs = dict(zip(list_A, list_B))

    then access individual dataframes with dfs['df1']:

    list_a = ['a', 'b', 'c']
    list_b = [1, 2, 3]
    d = dict(zip(list_a, list_b))
    print(d['a'])
    # 1
    

    or hack locals:

    for name, df in zip(list_A, list_B):
        locals()[name] = df
    

    Then you can access individual dataframes directly, df1, df2 etc:

    list_a = ['a', 'b', 'c']
    list_b = [1, 2, 3]
    for key, value in zip(list_a, list_b):
        locals()[key] = value
    print(a)
    #  1