Here's the general way of doing so with csv.DictReader
.
Start by loading the data:
import csv
import itertools
with open('stuff.csv', 'rb') as csvfile:
all_ = list(csv.DictReader(csvfile))
Now, you can use itertools.groupby
to group and process each group. For example
d = []
for k, g in itertools.groupby(
all_,
key=lambda r: (r['PrimaryId'], r[' LastName'])):
d.append({
'PrimaryId': k[0],
'LastName': k[1],
'CarName': [e[' CarName'] for e in g]
})
Will group by primary id and last name, and make a list of cars.
Once you have something like this, you can just use json.dumps().