Skip to content Skip to sidebar Skip to footer

Create A List Of Dictionaries In A Dictionary From Csv In Python

I have a csv that looks like this: Name;Category;Address McFood;Fast Food;Street 1 BurgerEmperor;Fast Food;Way 1 BlueFrenchHorn;French;Street 12 PetesPizza;Italian;whatever SubZero

Solution 1:

Using collections.defaultdict:

import csv
from collections import defaultdict

mydict = defaultdict(list)  # <---

with open ('food.csv', 'r') as csvfile:
    fileDialect = csv.Sniffer().sniff(csvfile.read(1024))
    csvfile.seek(0)
    dictReader = csv.DictReader(csvfile, dialect=fileDialect)
    for row in dictReader:
        mycategory= row.pop("Category")
        mydict[mycategory].append(row)  # Will put a list for not-existing key

mydict = dict(mydict)  # Convert back to a normal dictionary (optional)

Post a Comment for "Create A List Of Dictionaries In A Dictionary From Csv In Python"