Home > other >  Convert list type dictionary to pandas dataframe - python
Convert list type dictionary to pandas dataframe - python

Time:11-30

I want to convert dictionary which has two rows. the values are in the first row and keys are in the second row. Here is my dictionary.

{'data': [['1', 'Male', ['a,b,c'], 'USA'],['2', 'Male', ['r,g,e'], 'JAPAN'],['3', 'Female', ['f,r,b'], 'UK']],
 'columns': ['id', 'gender', 'array_userid' ,'location']}

I want to convert it into a pandas data framelike below:

     id     gender   array_userid   location
0    1      Male     ['a,b,c']      USA
1    2      Male     ['r,g,e']      JAPAN
3    3      Female   ['f,r,b']      UK

Any help will be appreciated. thanks in advanced.

CodePudding user response:

Use DataFrame constructor with select values of dictionary:

d = {'data': [['1', 'Male', ['a,b,c'], 'USA'],['2', 'Male', ['r,g,e'], 'JAPAN'],['3', 'Female', ['f,r,b'], 'UK']],
 'columns': ['id', 'gender', 'array_userid' ,'location']}

df = pd.DataFrame(data=d['data'], columns=d['columns'])
print (df)
  id  gender array_userid location
0  1    Male      [a,b,c]      USA
1  2    Male      [r,g,e]    JAPAN
2  3  Female      [f,r,b]       UK
  • Related