Megan
Megan

Reputation: 45

Searching Python dictionary for string

I have a dictionary of cities derived from a .csv. I am trying to allow users to search for a city, and have my program return the data for that city. However, I am not understanding how to write a "for" loop that iterates through the dictionary. Any advice?

Code:

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)

Upvotes: 0

Views: 5597

Answers (2)

Hello.World
Hello.World

Reputation: 740

Dictionary is collection of Key - Value pairs. For example:

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"

Upvotes: 0

mujjiga
mujjiga

Reputation: 16916

if myCity in worldCities:
    print (worldCities[myCity])
else:
    print('City not found.')

If all you want is just to print either the found values or 'City not found.' if there are no corresponding values, then you can use much shorter code

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

the get method of the dictionary object will return the value corresponding to the passed in key (first argument) and if the key do not exist it returns the default value which is the second argument of the get method. If no default value is passed a NoneType object is returned

Upvotes: 1

Related Questions