【问题标题】:Searching Python dictionary for string在 Python 字典中搜索字符串
【发布时间】:2019-03-10 20:40:27
【问题描述】:

我有一个来自 .csv 的城市字典。我试图让用户搜索一个城市,并让我的程序返回该城市的数据。但是,我不明白如何编写一个遍历字典的“for”循环。有什么建议吗?

代码:

import csv

#Step 4. Allow user to input a city and year
myCity = input('Pick a city: ')
myYear = ('yr'+(input('Choose a year you\'re interested in: ')))

#Step 1. Import and read CityPop.csv
with open(r'C:\Users\Megan\Desktop\G378_lab3\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['city']] = dict(row)        

    #Step 5. Search dictionary for matching values
    for row in worldCities:
            if dict(row[4]) == myCity:
                    pass
            else:
                    print('City not found.')
    print (row)

【问题讨论】:

  • 您能否发布您的数据样本?
  • 我们不知道输入数据(csv 文件)的结构。那么我们如何为您提供建议呢? :-P
  • 我觉得数据结构是这样的:year,something,info,etc,city name

标签: python dictionary search


【解决方案1】:
if myCity in worldCities:
    print (worldCities[myCity])
else:
    print('City not found.')

如果您只想打印找到的值或“未找到城市”。如果没有对应的值,那么你可以使用更短的代码

print (worldCities.get(myCity,'City not found.'))

字典对象的 get 方法将返回与传入键(第一个参数)对应的值,如果键不存在,则返回默认值,即 get 方法的第二个参数。如果没有传递默认值,则返回 NoneType 对象

【讨论】:

  • 不知道数据结构(csv文件)怎么写?
  • @s3no,正如问题中提到的,它是一个字典,问题要求搜索键,而且我们不必担心这个问题的字典中存储的值类型。
  • 在来自OP的原始代码源中,在循环for中,通过“行”来比较索引号[4]。这意味着“行”必须使用索引[4] 进行测试,而不是作为可迭代数据类型。所以我假设数据是多维的或表格的。如果我不知道数据结构,那么很难在数据结构中查找任何数据:-P。该行没有任何意义。第二个字典中可能嵌入了另一种字典类型。由于 OP 没有做出负面反应,我们可能猜到了数据的正确结构,现在已经无关紧要了。 :-)
  • @s3no 我同意你的观点,但我根据“worldCities[row['city']] = dict(row)” :-)
  • 太棒了!这行得通。尽管我确实有一个后续问题——如果我试图从 [myCity] 数据中提取特定年份的数据,这是正确的方法吗? if myYear in (worldCities): print (worldCities[myCity][myYear]) else: print('Year not found.')
【解决方案2】:

字典是键值对的集合。例如:

Let's create a dictionary with city - state pairs.

cities = {"New York City":"NY", "San Jose":"CA"}

In this dict, we have Key's as City and Values as their respective states. To iterate over this dict you can write a for loop like this:

for city, states in cities.items():
    print(city, states)

> "New York", "NY"
"San Jose", "CA"

For your example:

for key, value in worldCities.items():
    if key == "something":
        "then do something"
    else:
        "do something else"

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-10-02
    • 2022-11-19
    • 2016-07-04
    • 2017-04-21
    • 2023-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多