Outcast
Outcast

Reputation: 5117

Columns with list of keys and values to columns with lists of dicts

I have this in pandas:

  Key  Level       Subkeys     Values
0   A      0      [A1, A2]     [3, 4]
1   B      1          [B1]        [2]
2   C      2  [C1, C2, C3]  [8, 5, 1]

and I want to transform it to this:

  Key  Level                       Subdicts 
0   A      0              [{A1: 3, {A2: 4}]
1   B      1                       [{B1: 2]
2   C      2    [{C1: 8}, {C2: 5}, {C3: 1}]

What is the most efficient way to do this?

Upvotes: 0

Views: 38

Answers (1)

piRSquared
piRSquared

Reputation: 294228

I agree with cs95

This is pretty gross...

df.assign(Subdicts=[[{x: y} for x, y in zip(X, Y)] for X, Y in zip(df.Subkeys, df.Values)])

  Key  Level       Subkeys     Values                           Subdicts
0   A      0      [A1, A2]     [3, 4]             [{'A1': 3}, {'A2': 4}]
1   B      1          [B1]        [2]                        [{'B1': 2}]
2   C      2  [C1, C2, C3]  [8, 5, 1]  [{'C1': 8}, {'C2': 5}, {'C3': 1}]

Upvotes: 1

Related Questions