Create a Nested Dictionary from a Pandas Dataframe

Viewed 18

I have a dataframe with columns like this:

Name, Education, DOB, Job, Q1, Q2, Q3

I want to create a nested dictionary like this:

{
  Name: {
    Bio: {
      Education: {value},
      DOB: {value},
      Job: {value}
    },
    Questions: {
      Q1: {value},
      Q2: {value},
      Q3: {value}
    }
  }
}

How should I go about this?

1 Answers

You can just iterate over rows

nested_dict = {
    row['Name']: {
        'Bio': {
            'Education': row['Education'],
            'DOB': row['DOB'],
            'Job': row['Job']
        },
        'Questions': {
            'Q1': row['Q1'],
            'Q2': row['Q2'],
            'Q3': row['Q3'],
        }
    }
    for index, row in df.iterrows()
}
Related