Python:按字母顺序排列和排序

时间:2015-09-13 04:01:34

标签: python sorting csv dictionary

我需要编写一个接受用户输入年份的程序,并从CSV文件中读取信息,然后在屏幕上导出结果。 csv源文件的格式为:def __init__( self , vertices = None , color = rand_rgb() ): self.vertices = [rand_xy() for _ in range(N)] if vertices is None else vertices ,导出结果仅为男孩,格式为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... ")    

1 个答案:

答案 0 :(得分:2)

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