【问题标题】:Searching Python Dictionaries搜索 Python 字典
【发布时间】:2019-08-02 03:42:35
【问题描述】:

我正在尝试计算从 .csv 创建的字典中值的百分比变化。在 .csv 中,年份以“yr19--”格式存储在标题下。但是,当我使用下面的代码搜索值时,每次我得到“未找到年份”。 Dictionary in Python

#Step 4. Allow user to choose years
myYear1 = ('yr'+(input('Pick a year between 1970 and 2005 that ends in "0" or "5": ')))
myYear2 = ('yr'+(input('Now, pick another: ')))
#print('Let\'s calculate the percent change in population between',myYear1,'and',myYear2,'.')

#Step 1. Import and read CityPop.csv with open(r'C:\Users\Megan\Desktop\Megan3\CityPop.csv') as csv_file:
    reader = csv.DictReader(csv_file)

    #Step 2. Build dictionary to store .csv data
    worldCities = {}

    #Step 3. Use field names from .csv to create key and access attribute values
    for row in reader:
            worldCities[row['label']] = dict(row)

    #Step 5. Search dictionary for years
    if myYear1 in worldCities:

    #Step 6. Make sure input corresponds to file, return values to user
            yr1Val = (worldCities[row['myYear1']])
            print(yr1Val)
    else:
            print('Year not found.')

这是搜索字典的正确方法吗?我是否需要做一些不同的事情,因为标题在技术上是关键?

【问题讨论】:

  • 告诉我们你的代码中的readerworldCities是什么?
  • 明白了。添加有问题的链接!
  • 我们需要按照 shotgunner 的建议查看数据的 Python 表示,因为 CSV 不容易翻译。还要考虑更正您的代码缩进/格式。
  • 糟糕...我明白了。

标签: python csv dictionary search key


【解决方案1】:

我认为您的代码缩进是错误的。最后一个if 必须在for 循环范围内。你可以像这样搜索年份:

for row in reader:
    worldCities[row['label']] = dict(row)
    if myYear1 in worldCities[row['label']].keys():
        yr1Val = worldCities[row['label']][myYear1]
        print(yr1Val)
    else:
        print('Year not found.')

【讨论】:

    猜你喜欢
    • 2012-02-09
    • 2011-07-07
    • 2017-10-02
    • 1970-01-01
    • 2012-01-29
    • 1970-01-01
    相关资源
    最近更新 更多