0

This is the dictionary I have and I wanted to put every single value from the list into its own column.

my_dict  = {1: ['Home', 'Stories'], 2: ['Sounds', 'Stories', 'Home', 'Home', 'Stories'], 3: ['Journeys', 'Journeys', 'Journeys '], 4: [ 'Home', 'Home', 'Home'], 5: ['Home', 'Stories', 'Home', 'Home', 'Cancellation Flow'], 6: ['My Account', 'My Account']}

I would like my output to look like this:

User       1                  2                  3               4        5
1          'Home'            'Stories'
2          'Sounds'          'Stories'          'Home'          'Home'   'Stories'
3          'Journeys'        'Journeys'         'Journeys'
4          'Home'            'Home'             'Home'
5          'Home'            'Stories'          'Home'          'Home'   'Cancellation Flow'
6          'My Account'      'My Account'

Does anyone have any tips on how to do this. I wanted to make a sankey graph and need each singular click decision (each item of the list) as its own column in order to see the combination of each of these click decisions.

1 Answers1

0

You can take advantage from pandas lib which can automate a lot of efforts for such kind of tasks with concise code:

import pandas as pd

df = pd.DataFrame.from_dict(my_dict, orient='index').fillna('')\
    .rename_axis(['User']).reset_index()
df.columns = [df.columns[0], *(df.columns[1:] + 1)]
print(df)

   User           1           2          3     4                  5
0     1        Home     Stories                                    
1     2      Sounds     Stories       Home  Home            Stories
2     3    Journeys    Journeys  Journeys                          
3     4        Home        Home       Home                         
4     5        Home     Stories       Home  Home  Cancellation Flow
5     6  My Account  My Account                                    
RomanPerekhrest
  • 88,541
  • 4
  • 65
  • 105