user6882757
user6882757

Reputation:

How to convert dictionary key as row and values as columns

How to convert nested dictionary in to data frame

My dict is below

out =  {'1.2.2.2': {'DELETE': 1,
                'GET': 5,
                'POST': 1,
                'PUT': 3},
 '2.2.2.2': {'DELETE': 1,
                   'GET': 6,
                   'POST': 3,
                   'PUT': 3},
 '3.3.3.3': {'DELETE': 0,
               'GET': 6,
               'POST': 2,
               'PUT': 1}

I want to convert in to dataframe with column values IP, DELETE, DELETE, POST, PUT

IP key is not in my out

import dataframe
pd.DataFrame([out])
df.columns =['IP', 'DELETE', 'POST', 'PUT']

Upvotes: 1

Views: 2631

Answers (2)

braintho
braintho

Reputation: 401

out =  {'1.2.2.2': {'DELETE': 1,
                'GET': 5,
                'POST': 1,
                'PUT': 3},
 '2.2.2.2': {'DELETE': 1,
                   'GET': 6,
                   'POST': 3,
                   'PUT': 3},
 '3.3.3.3': {'DELETE': 0,
               'GET': 6,
               'POST': 2,
               'PUT': 1}}

Create the list of columns that you want included

cols = ['IP', 'DELETE', 'POST', 'PUT']

The following will transpose the dataframe, reset the index, and rename the previous index as 'IP'

pd.DataFrame(out).T.reset_index().rename(columns={'index':'IP'})[cols]

the output of this will be:

    IP  DELETE  POST    PUT
0   1.2.2.2 1   1   3
1   2.2.2.2 1   3   3
2   3.3.3.3 0   2   1

Upvotes: 1

Nora_F
Nora_F

Reputation: 451

You can do it like this:

df = pd.DataFrame(columns=['DELETE', 'POST', 'PUT'])
for item in out:
    list_dict = []
    list_dict.append({'DELETE':out[item]['DELETE'], 'POST':out[item]['POST'], 'PUT':out[item]['PUT']})
    df= df.append(list_dict)

and add a column named ID later. Like this:

df['ID']=[0]*len(df)

Here I made all the ids 0. You can change it according to your data.

Upvotes: 0

Related Questions