在Python字典中搜索字符串

问题描述 投票:0回答:2

我有一个源自.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)
python dictionary search
2个回答
1
投票
if myCity in worldCities:
    print (worldCities[myCity])
else:
    print('City not found.')

如果你想要的只是打印找到的值或'找不到城市'。如果没有相应的值,那么你可以使用更短的代码

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

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


0
投票

Dictionary是Key - Value对的集合。例如:

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"

© www.soinside.com 2019 - 2024. All rights reserved.