Python Forum
Load Comma Delimited csv to Nested Dictionary
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Load Comma Delimited csv to Nested Dictionary
#1
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.

Reply
#2
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']
Reply
#3
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.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Tab Delimited Strings? johnywhy 7 582 Jan-13-2024, 10:34 PM
Last Post: sgrey
  need to compare 2 values in a nested dictionary jss 2 867 Nov-30-2023, 03:17 PM
Last Post: Pedroski55
  [SOLVED] [BeautifulSoup] Turn select() into comma-separated string? Winfried 0 1,121 Aug-19-2022, 08:07 PM
Last Post: Winfried
  How to format Excel column with comma? dee 0 1,372 Jun-13-2022, 10:11 PM
Last Post: dee
  decimal comma DPaul 9 2,291 Feb-22-2022, 12:25 PM
Last Post: DeaD_EyE
  dataframe write to tab delimited differs from Excel koh 0 2,006 Aug-01-2021, 02:46 AM
Last Post: koh
  Adding a comma in the resulting value stsxbel 6 2,654 May-22-2021, 09:24 PM
Last Post: stsxbel
  Nested dictionary acting strange Pedroski55 2 2,103 May-13-2021, 10:37 PM
Last Post: Pedroski55
  format the output from a nested dictionary. nostradamus64 9 4,589 May-03-2021, 04:45 PM
Last Post: nostradamus64
Lightbulb Python Nested Dictionary michaelserra 2 2,617 Apr-18-2021, 07:54 AM
Last Post: michaelserra

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020