【问题标题】:Printing elements related to information in 'dict'打印与“dict”中的信息相关的元素
【发布时间】:2015-08-05 20:03:51
【问题描述】:

在理解“dict[]”命令时遇到了一点麻烦,如果有人能帮助我,将不胜感激。

这是我到目前为止的代码:(我已经输入了我需要帮助的位置和内容) 导入csv

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

使用上面的代码,我试图得到以下结果:

Popular boy names in year "2010" are: Aidan 119, Alex 224, Derek 143, Steven 212, Tom 111.....

来自以下输入:

File 2010:
2010, Steven, 212, Boy
2010, Mary, 423, Girl
2010 , Tom, 111, Boy
2010, Jessica, 223, Girl
(and so on)

【问题讨论】:

  • 提示:不要使用 dict 作为事物的名称,因为这会影响内置 dict() 函数。

标签: python list python-2.7 dictionary


【解决方案1】:

应该这样做:

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('\nBoys names in alphabetical order:')
for name in sorted(name_counts.keys()):
    print(name)

print('\nBoys names in alphabetical order and counts:')
for name, count in sorted(name_counts.items()):
    print('{}: {}'.format(name, count))

一些注意事项:

  1. 在 Python 2 中你应该使用raw_input,它在中变成了input Python 3。一种方法是让你的程序在 Python 2 中以相同的方式工作 和 3 会将其添加到文件的开头:

    import sys
    
    if sys.version_info.major < 3:
        input = raw_input
    

    现在无论 Python 版本是什么,您都可以使用input。

  2. 您的输入在逗号后有一个空格。由于只有 csv 阅读器 查找逗号,空格是列表中字符串的一部分 连续。用(entry.strip() for entry in row) 将其剥离即可解决 这个。

  3. 到目前为止,我比较的是年份的字符串。我可能值得转换 input_year 和 year 到 int 并比较它们。

使用问题中的示例文件运行程序看起来像这样:

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

【讨论】:

  • 男生名字旁边加个数可以排序吗?
  • @RelientFX 添加了带有计数的排序名称。
  • 所有计数都为 67?
  • 我在答案中添加了示例输出。
  • 谢谢@MikeMüller!实际上真的很有帮助
【解决方案2】:

dict[] 用于使用键检索存储在字典中的值。因此,如果您将上述内容存储为:

names = {'Steven': [212, 'Boy', 2010], 'Mary': [423, 'Girl', 2010]}

如果想检索 Steven 的信息,可以说 names['Steven'],这将返回列表 [212, 'Boy', 2010]。

我认为这不能完全回答您的问题,但应该可以帮助您入门。如果您想对字典进行预排序,您可能还想查看this。

【讨论】:

  • 那么对于我在上面发布的代码,您建议获得该结果的最佳方法是什么?
猜你喜欢
  • 2021-09-28
  • 2021-12-20
  • 1970-01-01
  • 1970-01-01
  • 2011-08-23
  • 1970-01-01
  • 1970-01-01
  • 2016-02-18
  • 1970-01-01
相关资源
最近更新 更多