0

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)
3
  • Can you please post sample of your data? Commented Mar 10, 2019 at 20:42
  • We do not know the structure of the input data (csv file). So how do we advise you? :-P Commented Mar 10, 2019 at 20:47
  • I think the data structure is like so: year,something,info,etc,city name Commented Mar 10, 2019 at 20:53

2 Answers 2

1
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

Sign up to request clarification or add additional context in comments.

6 Comments

How can you write this when you do not know the data structure (csv file)?
@s3no, As mentioned in the question it is a dictionary and the question asks for search on keys and moreover we don't have to worry about the kind of values stored in the dictionary for this question.
In the original code source from OP, in the loop for, there is a comparison of index number [4], through "rows". This means that "rows" must be tested with index [4] and not as the iterable data type. So I assumed that the data is multidimensional or tabular. If I do not know the data structure, then it's hard to look up any data in the data structure :-P. The row does not mean anything. There may be another dictionary type embedded in the second dictionary. Since the OP did not respond negatively, we probably guessed the right structure of the data, and now it is irrelevant. :-)
@s3no I agree with you, but I made that assumption based on the line "worldCities[row['city']] = dict(row)" :-)
Awesome! This worked. Although I do have a follow up question--if I am trying to pull the data for a specific year from the [myCity] data, is this the right way to do so? if myYear in (worldCities): print (worldCities[myCity][myYear]) else: print('Year not found.')
|
0

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.