繁体   English   中英

Python:字典和字母排序

[英]Python: dict and sorting in alphabetical

我需要编写一个程序来接受用户的输入年份并从CSV文件中读取信息,然后将结果导出到屏幕上。 csv源文件具有以下格式: year, name, count, gender和导出结果仅是男孩,其格式为Name Count按字母顺序排列。

输入文件:

2010,Ruby,440,Female

2010,Cooper,493,Male

输出:

Please enter the year: 2010
Popular boy names in year 2010 are:
     Aidan  112

运行程序时出现错误:

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 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()

我编辑了一下:

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... ")    

我做错了吗? 缩进还是……

结果:

>>> 
Please enter the year: 2013
Popular boy names in year 2013 are:
Print boy names... 
>>> 

您的csv文件中似乎有空行,这导致空row来循环csv文件。 在执行其余逻辑之前,您可以简单地检查row是否为空。 范例-

for row in  cvsFile:
    if row:
        year, name, count, gender = row  

        if (year == inputYear) and (gender == 'Boy'):
            dict[name] =  count

另外,您不应将dict用作变量名,它会掩盖内置函数dict()

另外,您的程序中还有另一个错别字-

sortedName = shorted(dict.keys())

我猜您打算使用sorted()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM