Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I read a CSV into a Python dictionary, where each key's value is a list of dicts?

I have a CSV file (staff) that looks like this:

id, name, title
1, Steve, Customer Service Manager
2, Martin, Warehouse Operator
3, Jonathan, Backend Developer

I want to parse this into the format:

staff = {
            '1':[{'name':'Steve'}, {'title':'Customer Service Manager'}],
            '2':[{'name':'Martin'}, {'title':'Warehouse Operator'}],
            '3':[{'name':'Jonathan'}, {'title':'Backend Developer'}]
        }

But as far as I can tell, the csvreader and pandas libraries don't support this type of operation. Is there a clean way to do this, perhaps with comprehension?

like image 485
eddiewastaken Avatar asked Feb 02 '26 14:02

eddiewastaken


1 Answers

I think DictReader may be a good solution:

with open("sample.csv", "r") as f_csv:
    reader = csv.DictReader(f_csv)
    data = [row for row in reader]
staff = {r["id"]: [{k: v} for k, v in r.items() if "id" not in k] for r in data}
print(staff)

output:

{'1': [{'name': 'Steve'}, {'title': 'Customer Service Manager'}], '2': [{'name': 'Martin'}, {'title': 'Warehouse Operator'}], '3': [{'name': 'Jonathan'}, {'title': 'Backend Developer'}]}

notes

I modified the csv not to have comma and space to separate fields. Also, this allows any number of other fields, rather than hardcoding just the two shown here. This also combines both dict and list comprehensions.

like image 138
theherk Avatar answered Feb 04 '26 07:02

theherk