Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading