Home > Software design >  separate multiple values from a key into their own key/value pairs
separate multiple values from a key into their own key/value pairs

Time:11-02

If we have the following list of dictionary:

df=[{'answers': ['Yes', 'No'], 'question': 'status', 'type': 'string'}]

How can I split the above list into two dictionaries with only single value for answers key:

df=[{'answers': ['Yes'], 'question': 'status', 'type': 'string'}, {'answers': ['No'], 'question': 'status', 'type': 'string'}]

Any guidance would be much appreciated. Thank you

CodePudding user response:

I think you mean you work with DataFrames (hence your variable name df). In that case pandas has already a function for this specific use case: explode:

import pandas as pd
df = pd.DataFrame([{'answers': ['Yes', 'No'], 'question': 'status', 'type': 'string'}])
print(df.explode('answers'))

Output:

  answers question    type
0     Yes   status  string
0      No   status  string

Edit: you can easily get back to a dictionary form with to_dict:

df = df.explode('answers')
print(df.to_dict(orient='records'))

Output:

[{'answers': 'Yes', 'question': 'status', 'type': 'string'}, {'answers': 'No', 'question': 'status', 'type': 'string'}]

CodePudding user response:

You can try this:

  import copy 
    df=[{'answers': ['Yes', 'No'], 'question': 'status', 'type': 'string'}]
    df2=copy.deepcopy(df)
    content = df[0]
    for x,y in content.items():
      if (len(y) > 1) and isinstance(y,list):
        df[0][x]=y[0]
        df2[0][x]=y[1]
    # print(df)
    print(df2)
    print(df)

however this works only for 2 lists not more

  • Related