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











up vote
5
down vote

favorite












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!










share|improve this question






















  • Check out the stdlib csv module. No need to parse the text file yourself
    – TheIncorrigible1
    Dec 3 at 18:22

















up vote
5
down vote

favorite












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!










share|improve this question






















  • Check out the stdlib csv module. No need to parse the text file yourself
    – TheIncorrigible1
    Dec 3 at 18:22















up vote
5
down vote

favorite









up vote
5
down vote

favorite











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!










share|improve this question













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!







python python-3.x dictionary






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Dec 3 at 18:17









H. Raydon

564




564












  • Check out the stdlib csv module. No need to parse the text file yourself
    – TheIncorrigible1
    Dec 3 at 18:22




















  • Check out the stdlib csv module. No need to parse the text file yourself
    – TheIncorrigible1
    Dec 3 at 18:22


















Check out the stdlib csv module. No need to parse the text file yourself
– TheIncorrigible1
Dec 3 at 18:22






Check out the stdlib csv module. No need to parse the text file yourself
– TheIncorrigible1
Dec 3 at 18:22














4 Answers
4






active

oldest

votes

















up vote
6
down vote













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}')





share|improve this answer






























    up vote
    0
    down vote













    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.






    share|improve this answer




























      up vote
      -1
      down vote













      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)





      share|improve this answer




























        up vote
        -1
        down vote













        I would save your data as a json, say state_flowers.json, in the following format:



            {
        "California":"Poppy",
        "West Virginia":"Rhododendron",
        ...
        }


        Then you can just set up your function to return flowers based on dictionary keys:



                search = input("Enter state name:")    #user enters input of state
        if state == search:
        print(state_flowers["%s" %state], "is the State Flower for", %state)


        This will use your state names as dictionary keys and retrieve the flowers associated with them from your json file.






        share|improve this answer























        • > The following text file I must read
          – TheIncorrigible1
          Dec 3 at 18:25












        • That would make sense if the primary purpose of this program was to read data from a text file, but it is not. It is to allow a user to input a value and have a value returned. Given that fact, using a comma separated txt file rather than a dictionary is a very inefficient way to go about this. The only reason that one would really need to use a text file in this situation is if this is a class assignment and they are using stack overflow to cheat on their homework. If this is a serious question, then the user is just better off scrapping the text file.
          – Jeremiah
          Dec 3 at 18:39













        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53599555%2fpython-creating-dictionaries-by-reading-text-files-and-searching-through-that%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        4 Answers
        4






        active

        oldest

        votes








        4 Answers
        4






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes








        up vote
        6
        down vote













        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}')





        share|improve this answer



























          up vote
          6
          down vote













          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}')





          share|improve this answer

























            up vote
            6
            down vote










            up vote
            6
            down vote









            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}')





            share|improve this answer














            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}')






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Dec 3 at 18:21

























            answered Dec 3 at 18:20









            jpp

            87.7k195099




            87.7k195099
























                up vote
                0
                down vote













                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.






                share|improve this answer

























                  up vote
                  0
                  down vote













                  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.






                  share|improve this answer























                    up vote
                    0
                    down vote










                    up vote
                    0
                    down vote









                    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.






                    share|improve this answer












                    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.







                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Dec 3 at 21:11









                    J-L

                    39619




                    39619






















                        up vote
                        -1
                        down vote













                        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)





                        share|improve this answer

























                          up vote
                          -1
                          down vote













                          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)





                          share|improve this answer























                            up vote
                            -1
                            down vote










                            up vote
                            -1
                            down vote









                            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)





                            share|improve this answer












                            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)






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Dec 3 at 18:24









                            ak_app

                            1287




                            1287






















                                up vote
                                -1
                                down vote













                                I would save your data as a json, say state_flowers.json, in the following format:



                                    {
                                "California":"Poppy",
                                "West Virginia":"Rhododendron",
                                ...
                                }


                                Then you can just set up your function to return flowers based on dictionary keys:



                                        search = input("Enter state name:")    #user enters input of state
                                if state == search:
                                print(state_flowers["%s" %state], "is the State Flower for", %state)


                                This will use your state names as dictionary keys and retrieve the flowers associated with them from your json file.






                                share|improve this answer























                                • > The following text file I must read
                                  – TheIncorrigible1
                                  Dec 3 at 18:25












                                • That would make sense if the primary purpose of this program was to read data from a text file, but it is not. It is to allow a user to input a value and have a value returned. Given that fact, using a comma separated txt file rather than a dictionary is a very inefficient way to go about this. The only reason that one would really need to use a text file in this situation is if this is a class assignment and they are using stack overflow to cheat on their homework. If this is a serious question, then the user is just better off scrapping the text file.
                                  – Jeremiah
                                  Dec 3 at 18:39

















                                up vote
                                -1
                                down vote













                                I would save your data as a json, say state_flowers.json, in the following format:



                                    {
                                "California":"Poppy",
                                "West Virginia":"Rhododendron",
                                ...
                                }


                                Then you can just set up your function to return flowers based on dictionary keys:



                                        search = input("Enter state name:")    #user enters input of state
                                if state == search:
                                print(state_flowers["%s" %state], "is the State Flower for", %state)


                                This will use your state names as dictionary keys and retrieve the flowers associated with them from your json file.






                                share|improve this answer























                                • > The following text file I must read
                                  – TheIncorrigible1
                                  Dec 3 at 18:25












                                • That would make sense if the primary purpose of this program was to read data from a text file, but it is not. It is to allow a user to input a value and have a value returned. Given that fact, using a comma separated txt file rather than a dictionary is a very inefficient way to go about this. The only reason that one would really need to use a text file in this situation is if this is a class assignment and they are using stack overflow to cheat on their homework. If this is a serious question, then the user is just better off scrapping the text file.
                                  – Jeremiah
                                  Dec 3 at 18:39















                                up vote
                                -1
                                down vote










                                up vote
                                -1
                                down vote









                                I would save your data as a json, say state_flowers.json, in the following format:



                                    {
                                "California":"Poppy",
                                "West Virginia":"Rhododendron",
                                ...
                                }


                                Then you can just set up your function to return flowers based on dictionary keys:



                                        search = input("Enter state name:")    #user enters input of state
                                if state == search:
                                print(state_flowers["%s" %state], "is the State Flower for", %state)


                                This will use your state names as dictionary keys and retrieve the flowers associated with them from your json file.






                                share|improve this answer














                                I would save your data as a json, say state_flowers.json, in the following format:



                                    {
                                "California":"Poppy",
                                "West Virginia":"Rhododendron",
                                ...
                                }


                                Then you can just set up your function to return flowers based on dictionary keys:



                                        search = input("Enter state name:")    #user enters input of state
                                if state == search:
                                print(state_flowers["%s" %state], "is the State Flower for", %state)


                                This will use your state names as dictionary keys and retrieve the flowers associated with them from your json file.







                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited Dec 3 at 18:25

























                                answered Dec 3 at 18:24









                                Jeremiah

                                1867




                                1867












                                • > The following text file I must read
                                  – TheIncorrigible1
                                  Dec 3 at 18:25












                                • That would make sense if the primary purpose of this program was to read data from a text file, but it is not. It is to allow a user to input a value and have a value returned. Given that fact, using a comma separated txt file rather than a dictionary is a very inefficient way to go about this. The only reason that one would really need to use a text file in this situation is if this is a class assignment and they are using stack overflow to cheat on their homework. If this is a serious question, then the user is just better off scrapping the text file.
                                  – Jeremiah
                                  Dec 3 at 18:39




















                                • > The following text file I must read
                                  – TheIncorrigible1
                                  Dec 3 at 18:25












                                • That would make sense if the primary purpose of this program was to read data from a text file, but it is not. It is to allow a user to input a value and have a value returned. Given that fact, using a comma separated txt file rather than a dictionary is a very inefficient way to go about this. The only reason that one would really need to use a text file in this situation is if this is a class assignment and they are using stack overflow to cheat on their homework. If this is a serious question, then the user is just better off scrapping the text file.
                                  – Jeremiah
                                  Dec 3 at 18:39


















                                > The following text file I must read
                                – TheIncorrigible1
                                Dec 3 at 18:25






                                > The following text file I must read
                                – TheIncorrigible1
                                Dec 3 at 18:25














                                That would make sense if the primary purpose of this program was to read data from a text file, but it is not. It is to allow a user to input a value and have a value returned. Given that fact, using a comma separated txt file rather than a dictionary is a very inefficient way to go about this. The only reason that one would really need to use a text file in this situation is if this is a class assignment and they are using stack overflow to cheat on their homework. If this is a serious question, then the user is just better off scrapping the text file.
                                – Jeremiah
                                Dec 3 at 18:39






                                That would make sense if the primary purpose of this program was to read data from a text file, but it is not. It is to allow a user to input a value and have a value returned. Given that fact, using a comma separated txt file rather than a dictionary is a very inefficient way to go about this. The only reason that one would really need to use a text file in this situation is if this is a class assignment and they are using stack overflow to cheat on their homework. If this is a serious question, then the user is just better off scrapping the text file.
                                – Jeremiah
                                Dec 3 at 18:39




















                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.





                                Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                Please pay close attention to the following guidance:


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53599555%2fpython-creating-dictionaries-by-reading-text-files-and-searching-through-that%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                Popular posts from this blog

                                How to change which sound is reproduced for terminal bell?

                                Title Spacing in Bjornstrup Chapter, Removing Chapter Number From Contents

                                Can I use Tabulator js library in my java Spring + Thymeleaf project?