Search code examples
listloopsdictionaryiterationdefaultdict

Create multiple lists and store them into a dictionary Python


Here's my situation. I got two lists:

  • A list which comes from DF column (OS_names)

  • A list with the unique values of that column (OS_values)

    OS_name = df['OS_name'].tolist()

    OS_values = df.OS_name.unique().tolist()

I want to create several lists (one per value in OS_values) like this :

t = []

for i in range(0,len(OS_name)-1):
    if OS_values[0] == OS_name[i]:
        t.append(1)
    else:
        t.append(0)

I want to create a list per each value in OS_value, then store them into a dictionary, and at the end creating a df from my dictionary. If you're able to insert the value as the key it would be great, but not necessary. I read the defaultdict may be helpful but I cannot find a way to use it.

thanks for the help and have a great day!


Solution

  • I did it at the very end.

    dict_stable_feature = dict()
    
    for col in df_stable:
        
        t1 = df[col].tolist()
        t2 = df[col].unique().tolist()
        
        for value in t2:
            
            t = []
            
            for i in range (0, len(t1)-1):
                
                if value == t1[i]:
                    
                    t.append(1)
                
                else:
                    
                    t.append(0)
                    
            cc = str(col)
            vv = "_" + str(value)
            cv = cc + vv
            
            dict_stable_feature[cv] = t