![]() |
Load Comma Delimited csv to Nested Dictionary - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: Python Coding (https://python-forum.io/forum-7.html) +--- Forum: General Coding Help (https://python-forum.io/forum-8.html) +--- Thread: Load Comma Delimited csv to Nested Dictionary (/thread-9832.html) |
Load Comma Delimited csv to Nested Dictionary - Huck - Apr-30-2018 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. RE: Load Comma Delimited csv to Nested Dictionary - killerrex - Apr-30-2018 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}')
RE: Load Comma Delimited csv to Nested Dictionary - Huck - Apr-30-2018 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. |