Python Forum

Full Version: Load Comma Delimited csv to Nested Dictionary
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I would like to load a comma delimited csv file into a nested dictionary.

I'm unable to attach the csv file...

Name,Gender,Occupation,Home Planet
Ford Prefect,Male,Researcher,Betelgeuse Seven
Arthur Dent,Male,Sandwich-Maker,Earth
Tricia McMillan,Female,Mathematician,Earth
Marvin,Unknown,Paranoid Android,Unknown

I think this is the structure I want...
people[‘Arthur’]
{‘Occupation’: ‘Sandwich-Maker’, ‘Home Planet’: ‘Earth’, ‘Gender’: ‘Male’,
‘Name’: ‘Arthur Dent’}

Then I would like to get ‘Home Planet’ totals.
Betelgeuse Seven = 1
Earth = 2
Unknown = 1

Then I would like to print 42 if Occupation = ‘Mathematician’.

No, this is not a homework assignment. I’m new to Python and want to understand nested dictionaries and how to iterate through them.

import csv
with open(r"C:\Hitchhiker.csv", "r") as f:
    reader = csv.reader(f, delimiter=",")
    next(reader, None)  # skip the headers (Can I use the headers?)
    ?
Thanks for any help.

I think the csv.DictReader is exactly what you want...
>>> import csv
>>> with open('Hitchhiker.csv', 'rt') as f:
...     reader = csv.DictReader(f, delimiter=',')
...     for row in reader:
...         print(row)
...     print(f'Header: {reader.fieldnames}')
Output:
OrderedDict([('Name', 'Ford Prefect'), ('Gender', 'Male'), ('Occupation', 'Researcher'), ('Home Planet', 'Betelgeuse Seven')]) OrderedDict([('Name', 'Arthur Dent'), ('Gender', 'Male'), ('Occupation', 'Sandwich-Maker'), ('Home Planet', 'Earth')]) OrderedDict([('Name', 'Tricia McMillan'), ('Gender', 'Female'), ('Occupation', 'Mathematician'), ('Home Planet', 'Earth')]) OrderedDict([('Name', 'Marvin'), ('Gender', 'Unknown'), ('Occupation', 'Paranoid Android'), ('Home Planet', 'Unknown')]) Header: ['Name', 'Gender', 'Occupation', 'Home Planet']
Thanks, killerrex. That looks like what I want. I'm still not sure how to specify the column name by heading.
I will need something like...
if row[Occupation] == 'Mathematician':
This is my latest attempt which is obviously wrong and gets a syntax error..
import csv
with open(r'C:\Users\delliott\Desktop\pythoncsv\Q3\Hitchhiker.csv', 'rt') as f:
    reader = csv.DictReader(f, delimiter=',')
    for row in reader:
        if (row (f'Header: {reader.fieldnames.Occupation}) == 'Mathematician'):
            print('42')
        print(row)
    print(f'Header: {reader.fieldnames}')

I finally got it with the square brackets...

if row ['Occupation'] == 'Mathematician':
import csv
with open(r'C:\Users\delliott\Desktop\pythoncsv\Q3\Hitchhiker.csv', 'rt') as f:
    reader = csv.DictReader(f, delimiter=',')
    for row in reader:
        if row ['Occupation'] == 'Mathematician':
            print('42')
        print(row)
    print(f'Header: {reader.fieldnames}')
Thanks for your help. Your reply got me started.