create dictionary of dataframes via for loop

Viewed 2231

I wish to create a dictionary of dataframes so I can pass into a function. Each dataframe is just a single line string.

Input:

test1=['1','2']
dn=['x','y']
Mag =['tet1','tet2']
pm=['1','2'] 

keys=[]
final_list=[]
df = pd.DataFrame()

for num1 in test1:
    for num2 in dn:
        for num3 in Mag:
            for num4 in pm:
                keys.append(f'sw{num4}O{num1}{num2}{num3}')
                final_list.append(f'mp{num4}-ghfg{num1}-{num2}-{num3}')
                df=pd.DataFrame(final_list)
                df.append(df)

d = {}
d= dict(zip(keys, df))

Output:

In d['sw1O1xtet1']

Out 0

Desired Output: a dataframe containing the single line string 'mp1-ghfg1-x-tet1' corresponding to its key... NOt sure how to fix this...

3 Answers

The following code snippet will provide you the desired output.

import pandas as pd
test1=['1','2']
dn=['x','y']
Mag =['tet1','tet2']
pm=['1','2'] 

keys=[]
final_list=[]

for num1 in test1:
    for num2 in dn:
        for num3 in Mag:
            for num4 in pm:
                keys.append(f'sw{num4}O{num1}{num2}{num3}')
                final_list.append(f'mp{num4}-ghfg{num1}-{num2}-{num3}')

d = {}
d = dict(zip(keys, final_list))

print(d['sw1O1xtet1'])

In order to understand what's wrong with your code, you can have a look at the result of zip

>>> [(a,b) for (a,b) in zip(keys, df)]
[('sw1O1xtet1', 0)]

So you should not pass the whole dataframe to zip, only the first column df[0]

Also pay attention to the indentation, as the last 2 lines in the loop should be after the loop, not inside

You can put each value in a dataframe before adding it to the dictionary. And you don't need the intermediate lists if you construct the dictionary directly by adding key-value pairs:

test1 = ['1', '2']
dn = ['x', 'y']
Mag = ['tet1', 'tet2']
pm = ['1', '2'] 

d = {}

for num1 in test1:
    for num2 in dn:
        for num3 in Mag:
            for num4 in pm:
                key = f'sw{num4}O{num1}{num2}{num3}'
                value = pd.DataFrame({'col1': [f'mp{num4}-ghfg{num1}-{num2}-{num3}']})
                d[key] = value
Related