I am currently am trying to create a nested dictionary from a csv file.
The CSV File represents how many people there are for each demographic region. In the nested dictionary each key is a region and the value is another dictionary. The inner dictionary uses the demographic as key and the number of people for its value.
Region,American,Asian,Black
midwest,2500,2300,2150
north,1200,2300,2300
south,1211,211,2100
Currently have:
def load_csv(filename):
data={}
with open(filename) as csvfile:
fh = csv.DictReader(csvfile)
for row in fh:
key = row.pop('Region')
data[key] = row
return data
Expected Output (must convert the numbers from strings to integers):
{'west':{'American': 2500, 'ASIAN': 2300, ...}, 'north':{'American': 1200, ..}...}
I'm getting stuck when running my code as it is giving me "KeyError: 'Region'"
.read_csvand.to_dict: justdef load_csv(filename): return pd.read_csv(filename, index_col=0).to_dict('index')[This just takes the first column as index, no matter what it is; you could also useindex_col='Region'and it would raise error ifRegioncolumn was missing]