Writing a file to a dictionary





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







1















I'm taking a CSC 110 project. I am trying use dictionaries for our assignment even though we haven't learned them yet.



I have a file of countries and how many medals they won separated by new line characters. EX:



Afghanistan
0
0
0
Albania
0
0
0
Algeria
0
2
0


Each line after the country is the medals they earned starting with gold and working its way down to bronze.



I want to take these and store them in a dictionary with the structure looking something like this.
dict={Afghanistan: [0,0,0], Albania: [0,0,0]}



What I have :



olympic_stats = {}
fileIn = open('test.txt', 'r')

line = fileIn.readline()#Initialize Loop
counter = 0
while line != '':
if counter == 4:
counter = 0

if counter%4 == 0:#First Pass, COUNTRY
country_name = line.rstrip()
elif counter%4 == 1:#Second Pass, GOLD
gold_medals = int(line)
elif counter%4 == 2:#Third Pass, SILVER
silver_medals = int(line)
else: #Fourth Pass, BRONZE
bronze_medals = int(line)

#update Counter
counter += 1
if counter == 4:
olympic_stats[country_name] = [gold_medals, silver_medals, bronze_medals]


line = fileIn.readline()#Update Loop


While this works it is nasty and over complicated. I'm trying to come up with a new way to do this.










share|improve this question































    1















    I'm taking a CSC 110 project. I am trying use dictionaries for our assignment even though we haven't learned them yet.



    I have a file of countries and how many medals they won separated by new line characters. EX:



    Afghanistan
    0
    0
    0
    Albania
    0
    0
    0
    Algeria
    0
    2
    0


    Each line after the country is the medals they earned starting with gold and working its way down to bronze.



    I want to take these and store them in a dictionary with the structure looking something like this.
    dict={Afghanistan: [0,0,0], Albania: [0,0,0]}



    What I have :



    olympic_stats = {}
    fileIn = open('test.txt', 'r')

    line = fileIn.readline()#Initialize Loop
    counter = 0
    while line != '':
    if counter == 4:
    counter = 0

    if counter%4 == 0:#First Pass, COUNTRY
    country_name = line.rstrip()
    elif counter%4 == 1:#Second Pass, GOLD
    gold_medals = int(line)
    elif counter%4 == 2:#Third Pass, SILVER
    silver_medals = int(line)
    else: #Fourth Pass, BRONZE
    bronze_medals = int(line)

    #update Counter
    counter += 1
    if counter == 4:
    olympic_stats[country_name] = [gold_medals, silver_medals, bronze_medals]


    line = fileIn.readline()#Update Loop


    While this works it is nasty and over complicated. I'm trying to come up with a new way to do this.










    share|improve this question



























      1












      1








      1








      I'm taking a CSC 110 project. I am trying use dictionaries for our assignment even though we haven't learned them yet.



      I have a file of countries and how many medals they won separated by new line characters. EX:



      Afghanistan
      0
      0
      0
      Albania
      0
      0
      0
      Algeria
      0
      2
      0


      Each line after the country is the medals they earned starting with gold and working its way down to bronze.



      I want to take these and store them in a dictionary with the structure looking something like this.
      dict={Afghanistan: [0,0,0], Albania: [0,0,0]}



      What I have :



      olympic_stats = {}
      fileIn = open('test.txt', 'r')

      line = fileIn.readline()#Initialize Loop
      counter = 0
      while line != '':
      if counter == 4:
      counter = 0

      if counter%4 == 0:#First Pass, COUNTRY
      country_name = line.rstrip()
      elif counter%4 == 1:#Second Pass, GOLD
      gold_medals = int(line)
      elif counter%4 == 2:#Third Pass, SILVER
      silver_medals = int(line)
      else: #Fourth Pass, BRONZE
      bronze_medals = int(line)

      #update Counter
      counter += 1
      if counter == 4:
      olympic_stats[country_name] = [gold_medals, silver_medals, bronze_medals]


      line = fileIn.readline()#Update Loop


      While this works it is nasty and over complicated. I'm trying to come up with a new way to do this.










      share|improve this question
















      I'm taking a CSC 110 project. I am trying use dictionaries for our assignment even though we haven't learned them yet.



      I have a file of countries and how many medals they won separated by new line characters. EX:



      Afghanistan
      0
      0
      0
      Albania
      0
      0
      0
      Algeria
      0
      2
      0


      Each line after the country is the medals they earned starting with gold and working its way down to bronze.



      I want to take these and store them in a dictionary with the structure looking something like this.
      dict={Afghanistan: [0,0,0], Albania: [0,0,0]}



      What I have :



      olympic_stats = {}
      fileIn = open('test.txt', 'r')

      line = fileIn.readline()#Initialize Loop
      counter = 0
      while line != '':
      if counter == 4:
      counter = 0

      if counter%4 == 0:#First Pass, COUNTRY
      country_name = line.rstrip()
      elif counter%4 == 1:#Second Pass, GOLD
      gold_medals = int(line)
      elif counter%4 == 2:#Third Pass, SILVER
      silver_medals = int(line)
      else: #Fourth Pass, BRONZE
      bronze_medals = int(line)

      #update Counter
      counter += 1
      if counter == 4:
      olympic_stats[country_name] = [gold_medals, silver_medals, bronze_medals]


      line = fileIn.readline()#Update Loop


      While this works it is nasty and over complicated. I'm trying to come up with a new way to do this.







      python






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited 2 days ago









      Community

      11




      11










      asked Nov 17 '18 at 2:36









      Luke KellyLuke Kelly

      877




      877
























          2 Answers
          2






          active

          oldest

          votes


















          1














          While your answer isn't super concise its not 'bad' per say. I might do something like this:



          olympic_stats = {}
          while line:
          line_str = line.rstrip()
          if line_str[0].isalpha():
          country = line_str
          olympic_stats[country] =

          else:
          olympic_stats[country].append(line_str)





          share|improve this answer
























          • I didn't know .isalpha() was something I could do. Is there an equivalent to that but for int? I just added a update statement for the line variable and this worked perfectly.

            – Luke Kelly
            Nov 17 '18 at 3:10











          • Sure is, isnumeric(). see docs here: tutorialspoint.com/python/string_isnumeric.htm If you don't expect any malformed input you won't need to have an elif statement though. Just convert the line_str to int like you do above and you should be good to go.

            – aegon52
            Nov 17 '18 at 3:19





















          0














          Your loop here is pretty clumsy - you can do better. You could, for example,




          • read the entire file at once into a list (using file.readlines())

          • count through the list four items at a time


          which I have done here:



          olympic_stats = {}
          fileIn = open('test.txt', 'r')
          fileLines = fileIn.readlines()
          counter = 0
          while counter < len(fileLines):
          country_name = fileLines[counter]
          gold_metals = fileLines[counter + 1]
          silver_metals = fileLines[counter + 2]
          bronze_metals = fileLines[counter + 3]

          olympic_stats[country_name] = [gold_medals, silver_medals, bronze_medals]
          counter += 4


          There are more concise but much more complicated methods of doing this, by involving list comprehension and numpy or itertools, but those are more advanced topics and this should suffice for the time being.



          While implementing this you might come up against errors when the number of lines in the file isn't easily divisible by four - I'll leave you to figure out how to fix that issue on your own, as it's a valuable learning experience and not too hard.






          share|improve this answer
























            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',
            autoActivateHeartbeat: false,
            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%2f53347687%2fwriting-a-file-to-a-dictionary%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            While your answer isn't super concise its not 'bad' per say. I might do something like this:



            olympic_stats = {}
            while line:
            line_str = line.rstrip()
            if line_str[0].isalpha():
            country = line_str
            olympic_stats[country] =

            else:
            olympic_stats[country].append(line_str)





            share|improve this answer
























            • I didn't know .isalpha() was something I could do. Is there an equivalent to that but for int? I just added a update statement for the line variable and this worked perfectly.

              – Luke Kelly
              Nov 17 '18 at 3:10











            • Sure is, isnumeric(). see docs here: tutorialspoint.com/python/string_isnumeric.htm If you don't expect any malformed input you won't need to have an elif statement though. Just convert the line_str to int like you do above and you should be good to go.

              – aegon52
              Nov 17 '18 at 3:19


















            1














            While your answer isn't super concise its not 'bad' per say. I might do something like this:



            olympic_stats = {}
            while line:
            line_str = line.rstrip()
            if line_str[0].isalpha():
            country = line_str
            olympic_stats[country] =

            else:
            olympic_stats[country].append(line_str)





            share|improve this answer
























            • I didn't know .isalpha() was something I could do. Is there an equivalent to that but for int? I just added a update statement for the line variable and this worked perfectly.

              – Luke Kelly
              Nov 17 '18 at 3:10











            • Sure is, isnumeric(). see docs here: tutorialspoint.com/python/string_isnumeric.htm If you don't expect any malformed input you won't need to have an elif statement though. Just convert the line_str to int like you do above and you should be good to go.

              – aegon52
              Nov 17 '18 at 3:19
















            1












            1








            1







            While your answer isn't super concise its not 'bad' per say. I might do something like this:



            olympic_stats = {}
            while line:
            line_str = line.rstrip()
            if line_str[0].isalpha():
            country = line_str
            olympic_stats[country] =

            else:
            olympic_stats[country].append(line_str)





            share|improve this answer













            While your answer isn't super concise its not 'bad' per say. I might do something like this:



            olympic_stats = {}
            while line:
            line_str = line.rstrip()
            if line_str[0].isalpha():
            country = line_str
            olympic_stats[country] =

            else:
            olympic_stats[country].append(line_str)






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Nov 17 '18 at 2:52









            aegon52aegon52

            586




            586













            • I didn't know .isalpha() was something I could do. Is there an equivalent to that but for int? I just added a update statement for the line variable and this worked perfectly.

              – Luke Kelly
              Nov 17 '18 at 3:10











            • Sure is, isnumeric(). see docs here: tutorialspoint.com/python/string_isnumeric.htm If you don't expect any malformed input you won't need to have an elif statement though. Just convert the line_str to int like you do above and you should be good to go.

              – aegon52
              Nov 17 '18 at 3:19





















            • I didn't know .isalpha() was something I could do. Is there an equivalent to that but for int? I just added a update statement for the line variable and this worked perfectly.

              – Luke Kelly
              Nov 17 '18 at 3:10











            • Sure is, isnumeric(). see docs here: tutorialspoint.com/python/string_isnumeric.htm If you don't expect any malformed input you won't need to have an elif statement though. Just convert the line_str to int like you do above and you should be good to go.

              – aegon52
              Nov 17 '18 at 3:19



















            I didn't know .isalpha() was something I could do. Is there an equivalent to that but for int? I just added a update statement for the line variable and this worked perfectly.

            – Luke Kelly
            Nov 17 '18 at 3:10





            I didn't know .isalpha() was something I could do. Is there an equivalent to that but for int? I just added a update statement for the line variable and this worked perfectly.

            – Luke Kelly
            Nov 17 '18 at 3:10













            Sure is, isnumeric(). see docs here: tutorialspoint.com/python/string_isnumeric.htm If you don't expect any malformed input you won't need to have an elif statement though. Just convert the line_str to int like you do above and you should be good to go.

            – aegon52
            Nov 17 '18 at 3:19







            Sure is, isnumeric(). see docs here: tutorialspoint.com/python/string_isnumeric.htm If you don't expect any malformed input you won't need to have an elif statement though. Just convert the line_str to int like you do above and you should be good to go.

            – aegon52
            Nov 17 '18 at 3:19















            0














            Your loop here is pretty clumsy - you can do better. You could, for example,




            • read the entire file at once into a list (using file.readlines())

            • count through the list four items at a time


            which I have done here:



            olympic_stats = {}
            fileIn = open('test.txt', 'r')
            fileLines = fileIn.readlines()
            counter = 0
            while counter < len(fileLines):
            country_name = fileLines[counter]
            gold_metals = fileLines[counter + 1]
            silver_metals = fileLines[counter + 2]
            bronze_metals = fileLines[counter + 3]

            olympic_stats[country_name] = [gold_medals, silver_medals, bronze_medals]
            counter += 4


            There are more concise but much more complicated methods of doing this, by involving list comprehension and numpy or itertools, but those are more advanced topics and this should suffice for the time being.



            While implementing this you might come up against errors when the number of lines in the file isn't easily divisible by four - I'll leave you to figure out how to fix that issue on your own, as it's a valuable learning experience and not too hard.






            share|improve this answer




























              0














              Your loop here is pretty clumsy - you can do better. You could, for example,




              • read the entire file at once into a list (using file.readlines())

              • count through the list four items at a time


              which I have done here:



              olympic_stats = {}
              fileIn = open('test.txt', 'r')
              fileLines = fileIn.readlines()
              counter = 0
              while counter < len(fileLines):
              country_name = fileLines[counter]
              gold_metals = fileLines[counter + 1]
              silver_metals = fileLines[counter + 2]
              bronze_metals = fileLines[counter + 3]

              olympic_stats[country_name] = [gold_medals, silver_medals, bronze_medals]
              counter += 4


              There are more concise but much more complicated methods of doing this, by involving list comprehension and numpy or itertools, but those are more advanced topics and this should suffice for the time being.



              While implementing this you might come up against errors when the number of lines in the file isn't easily divisible by four - I'll leave you to figure out how to fix that issue on your own, as it's a valuable learning experience and not too hard.






              share|improve this answer


























                0












                0








                0







                Your loop here is pretty clumsy - you can do better. You could, for example,




                • read the entire file at once into a list (using file.readlines())

                • count through the list four items at a time


                which I have done here:



                olympic_stats = {}
                fileIn = open('test.txt', 'r')
                fileLines = fileIn.readlines()
                counter = 0
                while counter < len(fileLines):
                country_name = fileLines[counter]
                gold_metals = fileLines[counter + 1]
                silver_metals = fileLines[counter + 2]
                bronze_metals = fileLines[counter + 3]

                olympic_stats[country_name] = [gold_medals, silver_medals, bronze_medals]
                counter += 4


                There are more concise but much more complicated methods of doing this, by involving list comprehension and numpy or itertools, but those are more advanced topics and this should suffice for the time being.



                While implementing this you might come up against errors when the number of lines in the file isn't easily divisible by four - I'll leave you to figure out how to fix that issue on your own, as it's a valuable learning experience and not too hard.






                share|improve this answer













                Your loop here is pretty clumsy - you can do better. You could, for example,




                • read the entire file at once into a list (using file.readlines())

                • count through the list four items at a time


                which I have done here:



                olympic_stats = {}
                fileIn = open('test.txt', 'r')
                fileLines = fileIn.readlines()
                counter = 0
                while counter < len(fileLines):
                country_name = fileLines[counter]
                gold_metals = fileLines[counter + 1]
                silver_metals = fileLines[counter + 2]
                bronze_metals = fileLines[counter + 3]

                olympic_stats[country_name] = [gold_medals, silver_medals, bronze_medals]
                counter += 4


                There are more concise but much more complicated methods of doing this, by involving list comprehension and numpy or itertools, but those are more advanced topics and this should suffice for the time being.



                While implementing this you might come up against errors when the number of lines in the file isn't easily divisible by four - I'll leave you to figure out how to fix that issue on your own, as it's a valuable learning experience and not too hard.







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 17 '18 at 2:51









                Green Cloak GuyGreen Cloak Guy

                3,4101721




                3,4101721






























                    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.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53347687%2fwriting-a-file-to-a-dictionary%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

                    List item for chat from Array inside array React Native

                    Thiostrepton

                    Caerphilly