简体   繁体   中英

Create a Nested Dictionary from a Pandas Dataframe

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?

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()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM