Printing elements related to information in 'dict'
有点不太明白"
这就是我迄今为止所拥有的代码:(我已经输入了我需要帮助的地方和内容)进口CSV
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | inputYear = input('Please enter the year: ') inFile = open('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) # According to information in 'dict', print (name, count) sorted by 'name' in alphabetical order print("Print boy names...") inFile.close() |
使用上面的代码,我试图得到以下结果:
1 | Popular boy names in year"2010" are: Aidan 119, Alex 224, Derek 143, Steven 212, Tom 111..... |
从以下输入:
1 2 3 4 5 6 | File 2010: 2010, Steven, 212, Boy 2010, Mary, 423, Girl 2010 , Tom, 111, Boy 2010, Jessica, 223, Girl (and so on) |
应该这样做:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | from __future__ import print_function import csv import sys if sys.version_info.major < 3: input = raw_input input_gender = 'Boy' # could make this a user-supplied value too input_year = input('Please enter the year: ').strip() file_name = 'babyQldAll.csv' with open(file_name) as fobj: csv_file = csv.reader(fobj) name_counts = {} for row in csv_file: year, name, count, gender = (entry.strip() for entry in row) if year == input_year and gender == input_gender: name_counts[name] = int(count) print('Popular {} names in year {} are:'.format(input_gender.lower(), input_year)) for name, count in name_counts.items(): print(name, count) print(' Boys names in alphabetical order:') for name in sorted(name_counts.keys()): print(name) print(' Boys names in alphabetical order and counts:') for name, count in sorted(name_counts.items()): print('{}: {}'.format(name, count)) |
一些注释:
在python2中,应该使用
1 2 3 4 | import sys if sys.version_info.major < 3: input = raw_input |
现在,无论什么样的Python版本,您都可以使用
您的输入在逗号后有一个空格。因为只有csv阅读器查找逗号,空格是列表中字符串的一部分一排。用
所以我比较了一年的字符串。我可能值得改变信仰同时,将
使用问题中的示例文件运行th程序看起来像thi:
1 2 3 4 5 6 7 8 9 10 11 12 | Please enter the year: 2010 Popular boy names in year 2010 are: Tom 111 Steven 212 Boys names in alphabetical order: Steven Tom Boys names in alphabetical order and counts: Steven: 212 Tom: 111 |
1 | names = {'Steven': [212, 'Boy', 2010], 'Mary': [423, 'Girl', 2010]} |
想要检索史蒂文的信息,你可以说是
我不认为这会完全回答你的问题,但它会帮助你开始。如果你想对字典进行预排序,你也可以看看这个。