我有一本从.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)
如果您只想打印找到的值或“City not found”。如果没有对应的值,则可以使用更短的代码
^{pr2}$dictionary对象的get方法将返回与传入的键(第一个参数)对应的值,如果该键不存在,则返回默认值,即get方法的第二个参数。如果没有传递默认值,则返回非类型对象
相关问题 更多 >
编程相关推荐