KeyError When Assigning Dictionary Keys and Values












4














I've recently begun learning Python and I wanted to write a script to extract the day of the month from a CSV column (formatted as YYYY/DD/MM) then compare website users to days of the month (and eventually weeks of the month) as a challenge/learning exercise. The gist is that it extracts the CSV info, formats it/converts to integers, and smushes it back together as a dictionary comparing days 1-31 with the number of site visitors.



My code is below. The error I'm receiving is 'KeyError: 1'on line 29 result[days] = users. I think I understand what is happening (kind of - I'm guessing it's not happy with the way I'm trying to assign values to an empty dictionary? It seems to be looking for the integer 1 as a key but not finding it?) but I can't figure out what to do next. I'm about 2 weeks into learning Python so I hope this isn't too stupid a question. What am I doing wrong? How can I make the columns at index [0] and [1] of users_by_day the key and value in my dictionary?



Note: I am learning and using Python 3.



 import csv
result = {}
with open('analytics.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_count = 0
users_by_day = list(csv_reader)
for row in users_by_day: #iterate through data

day = row[0].split('/') #split date to extract day of month

try: #skip unsplit cells

day = day[1]
except Exception as e:
pass
row[0] = day #set list column to extracted day value

users_by_day = users_by_day[1:-1] #strip headers

for row in users_by_day:
days = None
users = None

days = int(row[0]) #set values to int for math
users = int(row[1])

if days is not None:
if days in result: #trying to check for days in result
result[days] = users #where key error occurs
else:
result[days] += users

print(result)









share|improve this question




















  • 1




    The line result[days] = users wouldn't generate this error but result[days] += users would. First ensure which line is affected and better place a comment to this line instead of line numbers.
    – Michael Butscher
    Nov 21 at 1:21
















4














I've recently begun learning Python and I wanted to write a script to extract the day of the month from a CSV column (formatted as YYYY/DD/MM) then compare website users to days of the month (and eventually weeks of the month) as a challenge/learning exercise. The gist is that it extracts the CSV info, formats it/converts to integers, and smushes it back together as a dictionary comparing days 1-31 with the number of site visitors.



My code is below. The error I'm receiving is 'KeyError: 1'on line 29 result[days] = users. I think I understand what is happening (kind of - I'm guessing it's not happy with the way I'm trying to assign values to an empty dictionary? It seems to be looking for the integer 1 as a key but not finding it?) but I can't figure out what to do next. I'm about 2 weeks into learning Python so I hope this isn't too stupid a question. What am I doing wrong? How can I make the columns at index [0] and [1] of users_by_day the key and value in my dictionary?



Note: I am learning and using Python 3.



 import csv
result = {}
with open('analytics.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_count = 0
users_by_day = list(csv_reader)
for row in users_by_day: #iterate through data

day = row[0].split('/') #split date to extract day of month

try: #skip unsplit cells

day = day[1]
except Exception as e:
pass
row[0] = day #set list column to extracted day value

users_by_day = users_by_day[1:-1] #strip headers

for row in users_by_day:
days = None
users = None

days = int(row[0]) #set values to int for math
users = int(row[1])

if days is not None:
if days in result: #trying to check for days in result
result[days] = users #where key error occurs
else:
result[days] += users

print(result)









share|improve this question




















  • 1




    The line result[days] = users wouldn't generate this error but result[days] += users would. First ensure which line is affected and better place a comment to this line instead of line numbers.
    – Michael Butscher
    Nov 21 at 1:21














4












4








4


1





I've recently begun learning Python and I wanted to write a script to extract the day of the month from a CSV column (formatted as YYYY/DD/MM) then compare website users to days of the month (and eventually weeks of the month) as a challenge/learning exercise. The gist is that it extracts the CSV info, formats it/converts to integers, and smushes it back together as a dictionary comparing days 1-31 with the number of site visitors.



My code is below. The error I'm receiving is 'KeyError: 1'on line 29 result[days] = users. I think I understand what is happening (kind of - I'm guessing it's not happy with the way I'm trying to assign values to an empty dictionary? It seems to be looking for the integer 1 as a key but not finding it?) but I can't figure out what to do next. I'm about 2 weeks into learning Python so I hope this isn't too stupid a question. What am I doing wrong? How can I make the columns at index [0] and [1] of users_by_day the key and value in my dictionary?



Note: I am learning and using Python 3.



 import csv
result = {}
with open('analytics.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_count = 0
users_by_day = list(csv_reader)
for row in users_by_day: #iterate through data

day = row[0].split('/') #split date to extract day of month

try: #skip unsplit cells

day = day[1]
except Exception as e:
pass
row[0] = day #set list column to extracted day value

users_by_day = users_by_day[1:-1] #strip headers

for row in users_by_day:
days = None
users = None

days = int(row[0]) #set values to int for math
users = int(row[1])

if days is not None:
if days in result: #trying to check for days in result
result[days] = users #where key error occurs
else:
result[days] += users

print(result)









share|improve this question















I've recently begun learning Python and I wanted to write a script to extract the day of the month from a CSV column (formatted as YYYY/DD/MM) then compare website users to days of the month (and eventually weeks of the month) as a challenge/learning exercise. The gist is that it extracts the CSV info, formats it/converts to integers, and smushes it back together as a dictionary comparing days 1-31 with the number of site visitors.



My code is below. The error I'm receiving is 'KeyError: 1'on line 29 result[days] = users. I think I understand what is happening (kind of - I'm guessing it's not happy with the way I'm trying to assign values to an empty dictionary? It seems to be looking for the integer 1 as a key but not finding it?) but I can't figure out what to do next. I'm about 2 weeks into learning Python so I hope this isn't too stupid a question. What am I doing wrong? How can I make the columns at index [0] and [1] of users_by_day the key and value in my dictionary?



Note: I am learning and using Python 3.



 import csv
result = {}
with open('analytics.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
line_count = 0
users_by_day = list(csv_reader)
for row in users_by_day: #iterate through data

day = row[0].split('/') #split date to extract day of month

try: #skip unsplit cells

day = day[1]
except Exception as e:
pass
row[0] = day #set list column to extracted day value

users_by_day = users_by_day[1:-1] #strip headers

for row in users_by_day:
days = None
users = None

days = int(row[0]) #set values to int for math
users = int(row[1])

if days is not None:
if days in result: #trying to check for days in result
result[days] = users #where key error occurs
else:
result[days] += users

print(result)






python python-3.x csv dictionary keyerror






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Nov 21 at 1:19









Jaba

6,821175292




6,821175292










asked Nov 21 at 1:14









Grant Hendricks

234




234








  • 1




    The line result[days] = users wouldn't generate this error but result[days] += users would. First ensure which line is affected and better place a comment to this line instead of line numbers.
    – Michael Butscher
    Nov 21 at 1:21














  • 1




    The line result[days] = users wouldn't generate this error but result[days] += users would. First ensure which line is affected and better place a comment to this line instead of line numbers.
    – Michael Butscher
    Nov 21 at 1:21








1




1




The line result[days] = users wouldn't generate this error but result[days] += users would. First ensure which line is affected and better place a comment to this line instead of line numbers.
– Michael Butscher
Nov 21 at 1:21




The line result[days] = users wouldn't generate this error but result[days] += users would. First ensure which line is affected and better place a comment to this line instead of line numbers.
– Michael Butscher
Nov 21 at 1:21












3 Answers
3






active

oldest

votes


















1














The setdefault() call on dictionaries is great for this kind of thing, and is preferable to the if {thing} in {dict} construct.



So the following code:



if days in result:  # trying to check for days in result
result[days] = users # where key error occurs
else:
result[days] += users


Could become:



result.setdefault(days, 0)
result[days] += users





share|improve this answer





















  • This works great. Simple and elegant. I will research the function so I understand what it's doing better. Cheers.
    – Grant Hendricks
    Nov 21 at 17:30



















0














in the else part , if days not in result, the equation certainly would generate an error, because it using an key that dosent exit:



result[days] =result[days]+ users


but do you really mean like :



 if days is not None:
if days not in result: #if result doesn't have that day
result[days] = users #get the day and its value into result
else: #if result already has the day value
result[days] += users #summary the value





share|improve this answer





























    0














    Options aside from dicty.setdefault(key, val) and if key in dicty, include:



    Try / Except



    try:
    dicty[key] += value
    except KeyError:
    dicty[key] = value


    collections.defaultdict()



    Using collections.defaultdict():



    dicty = defaultdict(int)
    dicty[key] += value


    Last line will execute to the effect of dicty[key] = value or dicty[key] += value as appropriate (really what it does is, if the key is not found, run dicty[key] = int() before running dicty[key] += value ... you'd have to be careful using this for *= therefore).






    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%2f53403949%2fkeyerror-when-assigning-dictionary-keys-and-values%23new-answer', 'question_page');
      }
      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      The setdefault() call on dictionaries is great for this kind of thing, and is preferable to the if {thing} in {dict} construct.



      So the following code:



      if days in result:  # trying to check for days in result
      result[days] = users # where key error occurs
      else:
      result[days] += users


      Could become:



      result.setdefault(days, 0)
      result[days] += users





      share|improve this answer





















      • This works great. Simple and elegant. I will research the function so I understand what it's doing better. Cheers.
        – Grant Hendricks
        Nov 21 at 17:30
















      1














      The setdefault() call on dictionaries is great for this kind of thing, and is preferable to the if {thing} in {dict} construct.



      So the following code:



      if days in result:  # trying to check for days in result
      result[days] = users # where key error occurs
      else:
      result[days] += users


      Could become:



      result.setdefault(days, 0)
      result[days] += users





      share|improve this answer





















      • This works great. Simple and elegant. I will research the function so I understand what it's doing better. Cheers.
        – Grant Hendricks
        Nov 21 at 17:30














      1












      1








      1






      The setdefault() call on dictionaries is great for this kind of thing, and is preferable to the if {thing} in {dict} construct.



      So the following code:



      if days in result:  # trying to check for days in result
      result[days] = users # where key error occurs
      else:
      result[days] += users


      Could become:



      result.setdefault(days, 0)
      result[days] += users





      share|improve this answer












      The setdefault() call on dictionaries is great for this kind of thing, and is preferable to the if {thing} in {dict} construct.



      So the following code:



      if days in result:  # trying to check for days in result
      result[days] = users # where key error occurs
      else:
      result[days] += users


      Could become:



      result.setdefault(days, 0)
      result[days] += users






      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Nov 21 at 1:29









      Jonah Bishop

      8,37232957




      8,37232957












      • This works great. Simple and elegant. I will research the function so I understand what it's doing better. Cheers.
        – Grant Hendricks
        Nov 21 at 17:30


















      • This works great. Simple and elegant. I will research the function so I understand what it's doing better. Cheers.
        – Grant Hendricks
        Nov 21 at 17:30
















      This works great. Simple and elegant. I will research the function so I understand what it's doing better. Cheers.
      – Grant Hendricks
      Nov 21 at 17:30




      This works great. Simple and elegant. I will research the function so I understand what it's doing better. Cheers.
      – Grant Hendricks
      Nov 21 at 17:30













      0














      in the else part , if days not in result, the equation certainly would generate an error, because it using an key that dosent exit:



      result[days] =result[days]+ users


      but do you really mean like :



       if days is not None:
      if days not in result: #if result doesn't have that day
      result[days] = users #get the day and its value into result
      else: #if result already has the day value
      result[days] += users #summary the value





      share|improve this answer


























        0














        in the else part , if days not in result, the equation certainly would generate an error, because it using an key that dosent exit:



        result[days] =result[days]+ users


        but do you really mean like :



         if days is not None:
        if days not in result: #if result doesn't have that day
        result[days] = users #get the day and its value into result
        else: #if result already has the day value
        result[days] += users #summary the value





        share|improve this answer
























          0












          0








          0






          in the else part , if days not in result, the equation certainly would generate an error, because it using an key that dosent exit:



          result[days] =result[days]+ users


          but do you really mean like :



           if days is not None:
          if days not in result: #if result doesn't have that day
          result[days] = users #get the day and its value into result
          else: #if result already has the day value
          result[days] += users #summary the value





          share|improve this answer












          in the else part , if days not in result, the equation certainly would generate an error, because it using an key that dosent exit:



          result[days] =result[days]+ users


          but do you really mean like :



           if days is not None:
          if days not in result: #if result doesn't have that day
          result[days] = users #get the day and its value into result
          else: #if result already has the day value
          result[days] += users #summary the value






          share|improve this answer












          share|improve this answer



          share|improve this answer










          answered Nov 21 at 1:44









          Lee Jack

          588




          588























              0














              Options aside from dicty.setdefault(key, val) and if key in dicty, include:



              Try / Except



              try:
              dicty[key] += value
              except KeyError:
              dicty[key] = value


              collections.defaultdict()



              Using collections.defaultdict():



              dicty = defaultdict(int)
              dicty[key] += value


              Last line will execute to the effect of dicty[key] = value or dicty[key] += value as appropriate (really what it does is, if the key is not found, run dicty[key] = int() before running dicty[key] += value ... you'd have to be careful using this for *= therefore).






              share|improve this answer


























                0














                Options aside from dicty.setdefault(key, val) and if key in dicty, include:



                Try / Except



                try:
                dicty[key] += value
                except KeyError:
                dicty[key] = value


                collections.defaultdict()



                Using collections.defaultdict():



                dicty = defaultdict(int)
                dicty[key] += value


                Last line will execute to the effect of dicty[key] = value or dicty[key] += value as appropriate (really what it does is, if the key is not found, run dicty[key] = int() before running dicty[key] += value ... you'd have to be careful using this for *= therefore).






                share|improve this answer
























                  0












                  0








                  0






                  Options aside from dicty.setdefault(key, val) and if key in dicty, include:



                  Try / Except



                  try:
                  dicty[key] += value
                  except KeyError:
                  dicty[key] = value


                  collections.defaultdict()



                  Using collections.defaultdict():



                  dicty = defaultdict(int)
                  dicty[key] += value


                  Last line will execute to the effect of dicty[key] = value or dicty[key] += value as appropriate (really what it does is, if the key is not found, run dicty[key] = int() before running dicty[key] += value ... you'd have to be careful using this for *= therefore).






                  share|improve this answer












                  Options aside from dicty.setdefault(key, val) and if key in dicty, include:



                  Try / Except



                  try:
                  dicty[key] += value
                  except KeyError:
                  dicty[key] = value


                  collections.defaultdict()



                  Using collections.defaultdict():



                  dicty = defaultdict(int)
                  dicty[key] += value


                  Last line will execute to the effect of dicty[key] = value or dicty[key] += value as appropriate (really what it does is, if the key is not found, run dicty[key] = int() before running dicty[key] += value ... you'd have to be careful using this for *= therefore).







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Nov 21 at 1:45









                  NotAnAmbiTurner

                  745521




                  745521






























                      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%2f53403949%2fkeyerror-when-assigning-dictionary-keys-and-values%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

                      404 Error Contact Form 7 ajax form submitting

                      How to know if a Active Directory user can login interactively

                      TypeError: fit_transform() missing 1 required positional argument: 'X'