Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

KeyError When Assigning Dictionary Keys and Values

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)
like image 363
Grant Hendricks Avatar asked Nov 21 '18 01:11

Grant Hendricks


People also ask

Why do I get keyerror in Python dictionary?

Specifically for Methods which are used for retrieving keys/values from dictionary may raise errors like KeyError. A KeyError is raised by Python when a key doesn’t exist inside dictionary but your using some method to access that key. Exception raised by Python, when it doesn’t find key inside dictionary which its looking for.

How to access key-value in dictionary in Python?

Python | Accessing Key-value in Dictionary. Dictionary is quite a useful data structure in programming that is usually used to hash a particular key with value, so that they can be retrieved efficiently. Let’s discuss various ways of accessing all the keys along with their values in Python Dictionary. Method #1 : Using in operator.

What is a key error in Python?

In Python key error is raised when the key does not exist in the dictionary that is used to look up the value. For example, suppose you have a dictionary that contains key-value pair within the curly brackets and now if you want to get the particular key from the dictionary which does not exist in the given dictionary then it will raise an error.

How do I get the value of a failed dictionary key?

If the KeyError is raised from a failed dictionary key lookup in your own code, you can use .get () to return either the value found at the specified key or a default value. Much like the age retrieval example from before, the following example shows a better way to get the age from the dictionary using the key provided at the prompt:


Video Answer


2 Answers

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
like image 190
Jonah Bishop Avatar answered Oct 13 '22 18:10

Jonah Bishop


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
like image 27
Lee Jack Avatar answered Oct 13 '22 17:10

Lee Jack