Reputation: 25
I require to write a program which accept input year from user and read information from CSV file then export result on the screen. The csv source file has format: year, name, count, gender
and export result are boy only with format Name Count
in alphabetical order.
Input file:
2010,Ruby,440,Female
2010,Cooper,493,Male
Output:
Please enter the year: 2010
Popular boy names in year 2010 are:
Aidan 112
I have error when run program:
Please enter the year: 2014
Traceback (most recent call last):
File "E:\SIT111\A1\printBoynameTPL.py", line 26, in <module>
year, name, count, gender = row
ValueError: need more than 0 values to unpack
This is my code:
'''
This program accepts a year as input from a user and print boys' information of the year. The output should be sorted by name in alphabetical order.
Steps:
1. Receive a year from a user
2. Read CSV files:
Format: year, name, count, gender
3. Display popular boy names on the screen:
Format: Name Count
'''
import csv
inputYear = raw_input('Please enter the year: ')
inFile = open('output/babyQldAll.csv', 'rU')
cvsFile = csv.reader(inFile, delimiter=',')
dict = {}
for row in cvsFile:
year, name, count, gender = row
if (year == inputYear) and (gender == 'Boy'):
dict[name] = count
print('Popular boy names in year %s are:' % inputYear)
# +++++ You code here ++++
# According to informaiton in 'dict', print (name, count) sorted by 'name' in alphabetical order
sortedName = shorted(dict.keys())
for name in sortedName:
print(name, dict[name])
print("Print boy names... ")
inFile.close()
I edited a bit:
for row in cvsFile:
if row:
year, name, count, gender = row
if (year == inputYear) and (gender == 'Male'):
dict[name] = count
print('Popular boy names in year %s are:' % inputYear)
# +++++ You code here ++++
# According to informaiton in 'dict', print (name, count) sorted by 'name' in alphabetical order
sortedName = sorted(dict.keys())
for name in sortedName:
print(name,dict[name])
print("Print boy names... ")
did i do sth wrong? indents or sth?
result:
>>>
Please enter the year: 2013
Popular boy names in year 2013 are:
Print boy names...
>>>
Upvotes: 1
Views: 154
Reputation: 90979
You seem to be having empty lines in your csv file, which is causing empty row
to come you iterate the csv file. You can simply check if row
is empty or not, before doing rest of the logic. Example -
for row in cvsFile:
if row:
year, name, count, gender = row
if (year == inputYear) and (gender == 'Boy'):
dict[name] = count
Also, you should not use dict
as a variable name, it shadows the built-in function dict()
.
Also, you have another typo in your program -
sortedName = shorted(dict.keys())
I am guessing you intended to use sorted()
.
Upvotes: 2