Transform specified pandas columns into a list of dictionaries

Viewed 38

Current table:

source target value group
Bob dog 3 1
Kate cat 4 2
Sasha whale 5 3

Desired output:

list_dicts = [{'id': 'Bob', 'group': 1}, {'id':'Kate', 'group':2}, {'id': 'Sasha', 'group': 3}, 
              {'id': 'dog', 'group': 1}, {'id': 'cat', 'group': 2}, {'id': 'whale', 'group': 3}]

For the moment I am only able to do this:

df = df.to_dict('records')

I assume that to go further, I'd have to select the columns which I want to transform into list of dictionaries ? In this case I do not need the "value" column. #sendhelp

1 Answers

Use DataFrame.melt with specify columns for processing, then change order of columns and last convert to list of dictionaries:

L = (df.melt(id_vars='group', 
             value_vars=['source','target'], 
             value_name='id')[['id','group']].to_dict('records'))
print (L)
[{'id': 'Bob', 'group': 1}, {'id': 'Kate', 'group': 2}, {'id': 'Sasha', 'group': 3}, 
 {'id': 'dog', 'group': 1}, {'id': 'cat', 'group': 2}, {'id': 'whale', 'group': 3}]

If need processing all columns:

L1 = (df.melt(id_vars='group',
             value_name='id')[['id','group']].to_dict('records'))
print (L1)
[{'id': 'Bob', 'group': 1}, {'id': 'Kate', 'group': 2}, {'id': 'Sasha', 'group': 3},
 {'id': 'dog', 'group': 1}, {'id': 'cat', 'group': 2}, {'id': 'whale', 'group': 3},
 {'id': 3, 'group': 1}, {'id': 4, 'group': 2}, {'id': 5, 'group': 3}]
Related