Mohan
Mohan

Reputation: 1

Read CSV file and Provide output in list of dictionary format

I have the below CSV file with the given headers stored in my desktop.

Role_Name, entitlements
R1, Ent1
R1, Ent2
R1, Ent3
R2, Ent1
R2, Ent5
R2, Ent6
R3, Ent1
R3, Ent5

The Python code should prompt for the location of the above csv file. After me providing the location of the CSV file, it should print the output in the below format:

list =[{
  "R1":[Ent1,Ent2,Ent3]
},
{
"R2":[Ent1,Ent5,Ent6]
},
{
"R3":[Ent1,Ent5]
}
]

Upvotes: 0

Views: 36

Answers (1)

deadshot
deadshot

Reputation: 9061

Try this:

import pandas as pd
df = pd.read_csv('test.csv')
res = [{x: y.entitlements.to_list()} for x, y in df.groupby('Role_Name')]

Output:

[{'R1': [' Ent1', ' Ent2', ' Ent3']},
 {'R2': [' Ent1', ' Ent5', ' Ent6']},
 {'R3': [' Ent1', ' Ent5']}]

Upvotes: 1

Related Questions