H. Raydon
H. Raydon

Reputation: 133

Python - Creating Dictionaries by reading text files and searching through that dictionary

I must create a program that takes a user's input of a State and it returns that States state flower. The following text file I must read is called "state_flowers.txt" and it contains the following data

California,Poppy
West Virginia,Rhododendron
South Dakota,Pasque Flower
Connecticut,Mountain Laurel
New York,Rose
Georgia,Cherokee Rose
Washington,Coast Rhododendron
Virgina,American Dogwood
Arizona,Saguaro Cactus
Hawaii,Pua Aloalo
Alabama,Camelia
Illinois,Violet
Indiana,Peony
Delaware,Peach Blossom
Iowa,Wild Prairie Rose
Kansas,Sunflower
Alaska,Forget Me Not
Lousiana,Magnolia
Maine,White Pine Tassel
Massachusetts,Trailing Arbutus
Michigan,Apple Blossom
Minnesota,Lady Slipper
Mississippi,Magnolia
Missouri,Hawthorn
Montana,Bitterroot
Nebraska,Goldenrod
Nevada,Sagebrush
New Hampshire,Lilac
New Jersy,Violet
New Mexico,Yucca Flower
etc......

The problem that I'm experiencing with my code is that it will only ask for the input of the state's name and continue to do that over and over again with no output. Here is what I have for code so far:

d = {}
myFile = open('state_flowers.txt', 'r')
for line in myFile:
    line2=line.split(",")
    state = line2[0]
    flower = line2[1]
    c = len(flower)-1 
    #Strips the new line symbol
    flower = flower[0:c]
    d[state] = flower 
    #matches each state with its flower

for state, flower in d.items():   
    search = input("Enter state name:")    #user enters input of state
    if state == search:                   
        print(flower, "is the State Flower for", state)

As I said, all my program asks for is the input over and over again. So it does as such:

Enter state name:Maine
Enter state name:Califorina
Enter state name:Texas
Enter state name:
Enter state name:

I feel as if I'm very close on this, any help is appreciated and a clear explanation of what I am doing incorrectly would be much appreciated! Thank you!

Upvotes: 7

Views: 2709

Answers (4)

user10873885
user10873885

Reputation:

You can simply do this with Python 3.6+:

print(f'{d.get(search)} is the State Flower for {search}')

Upvotes: 0

J-L
J-L

Reputation: 1901

Your problem is that in your code:

for state, flower in d.items():   
    search = input("Enter state name:")    #user enters input of state
    if state == search:                   
        print(flower, "is the State Flower for", state)

you loop through all the state/flower pairs, and ask for a state name, each time. So if you have fifty state/flower pairs, the user will be asked fifty times. This is not what you want.

Instead, move the line that contains the input(...) statement to outside (that is, before) the loop. What way, the loop won't begin until after it's asked for.

As for the input line and the loop:

search = input("Enter state name:")    #user enters input of state
for state, flower in d.items():   
    if state == search:                   
        print(flower, "is the State Flower for", state)

consider replacing it with three non-loop lines:

state = input("Enter state name: ")
flower = d[state]
print(flower, "is the State Flower for", state)

And that's it. There's nothing to manually search for in a loop, since a dict object will search for you.

If you're concerned that the user mis-types a state name and you don't want your program to throw an exception, you can change the flower = d[state] line to:

flower = d.get(state, 'Nothing')

d.get(state) works pretty much the same way as d[state], except that you can specify what to set flower to (in this case, "Nothing") if the state isn't found in the dict.

Upvotes: 1

ak_app
ak_app

Reputation: 170

You can try a simple debugging. Print the values of "state" and "search" just before the comparison condition. This condition isn't getting "True" hence it just iterates for user input:

for state, flower in d.items():   
    search = input("Enter state name:")    #user enters input of state
    if state == search: 
        print(state,search)                  
        print(flower, "is the State Flower for", state)

Upvotes: -1

jpp
jpp

Reputation: 164673

You are close. There's no need to iterate your dictionary. The beauty of dict is it offers O(1) access to values given a key. You can just take your input and feed the key to your dictionary:

search = input("Enter state name:")    #user enters input of state
print(d.get(search), "is the State Flower for", search)

With Python 3.6+, you can write this more clearly using f-strings:

print(f'{d.get(search)} is the State Flower for {search}')

If the state doesn't exist in your dictionary d.get(search) will return None. If you don't want to print anything in this situation, you can use an if statement:

search = input("Enter state name:")    #user enters input of state
if search in d:
    print(f'{d[search]} is the State Flower for {search}')

Upvotes: 8

Related Questions