Xin
Xin

Reputation: 674

Converting data frame into a nested dictionary

Below is my subsetted data frame, I am having a hard time trying to convert it into my desired output as I am fairly new to Python. Essentially I want to create a nested dictionary inside a list, with the column names as a value, and then another nested dictionary inside a list. Is this doable?

import pandas as pd

    Sector             Community Name
0   centre: 10901.0    park: 3238.0
1   northeast: 6958.0  heights: 1955.0

Desired output:

[{'column': 'Sector',
  'value': [{'name': 'centre', 'value': 10901.0},
   {'name': 'northeast', 'value': 6958.0}]},

  {'column': 'Community Name',
    'value': [{'name': 'park', 'value': 3238.0},
     {'name': 'heights', 'value': 1955.0},
     {'name': 'hill', 'value': 1454.0}]}]

Upvotes: 0

Views: 56

Answers (2)

gunsodo
gunsodo

Reputation: 175

From @sushanth's answer, I may add up to this solution. Assume that your dataframe variable is defined as df.

result = []
for header in list(df):
    column_values = df[header].to_list()
    result.append({
        "column" : header,
        "value" : [dict(zip(['name', 'value'], str(value).split(":"))) for value in column_values]
    })

Upvotes: 1

sushanth
sushanth

Reputation: 8302

Using pandas in above case might be a overkill, Here is a solution using python inbuilt functions which you can give a try,

input_ = {"Sector": ["centre: 10901.0", "northeast: 6958.0"],
          "Community Name": ["park: 3238.0", "heights: 1955.0"]}

result = []
for k, v in input_.items():
    result.append({
        "column" : k,
        "value" : [dict(zip(['name', 'value'], vv.split(":"))) for vv in v]
    })

print(result)

[{'column': 'Sector',
  'value': [{'name': 'centre', 'value': ' 10901.0'},
            {'name': 'northeast', 'value': ' 6958.0'}]},
 {'column': 'Community Name',
  'value': [{'name': 'park', 'value': ' 3238.0'},
            {'name': 'heights', 'value': ' 1955.0'}]}]

Upvotes: 1

Related Questions