【发布时间】: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