Looping through multiple values in a dict python

Viewed 27

I have a dict with values that are like the following:

something_dict = { 
             'item1' : 'value1',
             'item2' : 'value2',
             'item3' : 'value3',
             'item4' : [ 
                      'category1' : 'value1',
                      'category2' : 'value2',
                      'category3' : 'value3'
                         ]                          ]

                } 

I'm trying to create 2 dataframes that will look like this

1st df

category1 | category2 | category3 
value1 | value2 | value3  

2nd df

item1 | item2 | item3 
value1 | value2 | value3 

so far I've tried the following code which only returns the last row

something = something_dict['item4']

1st_df = {} 
for i in range(len(something)):
    something_df['item1'] = something[i]['value1']
    something_df['item2']  = something[i]['value2']
    something_df['item3']  = something[i]['value3']
1 Answers

Assuming this to be the proper formatting of something_dict:

something_dict = { 
    'item1' : 'value1',
    'item2' : 'value2',
    'item3' : 'value3',
    'item4' : {
      'category1' : 'value1',
      'category2' : 'value2',
      'category3' : 'value3',
      },
}

Then you can do:

import pandas as pd

df1 = pd.DataFrame(something_dict.pop('item4'), index=[0])
df2 = pd.DataFrame(something_dict, index=[0])

print(df1)
# output:
#   category1 category2 category3
# 0    value1    value2    value3

print(df2)
# output:
#     item1   item2   item3
# 0  value1  value2  value3
Related