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)
python python-3.x csv dictionary keyerror
add a comment |
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
1
The lineresult[days] = users
wouldn't generate this error butresult[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
add a comment |
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
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
python python-3.x csv dictionary keyerror
edited Nov 21 at 1:19
Jaba
6,821175292
6,821175292
asked Nov 21 at 1:14
Grant Hendricks
234
234
1
The lineresult[days] = users
wouldn't generate this error butresult[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
add a comment |
1
The lineresult[days] = users
wouldn't generate this error butresult[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
add a comment |
3 Answers
3
active
oldest
votes
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
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
add a comment |
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
add a comment |
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).
add a comment |
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
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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
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
add a comment |
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
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
add a comment |
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
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
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
add a comment |
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
add a comment |
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
add a comment |
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
add a comment |
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
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
answered Nov 21 at 1:44
Lee Jack
588
588
add a comment |
add a comment |
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).
add a comment |
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).
add a comment |
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).
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).
answered Nov 21 at 1:45
NotAnAmbiTurner
745521
745521
add a comment |
add a comment |
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.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
1
The line
result[days] = users
wouldn't generate this error butresult[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