Reputation: 313
I'm using a similar method in a function I'm using. Why do I get a key error when I try to do this?
def trial():
adict={}
for x in [1,2,3]:
for y in [1,2]:
adict[y] += x
print(adict)
Upvotes: 0
Views: 1447
Reputation: 888
There is no value assigned to adict[y]
when you first use it.
def trial():
adict={}
for x in [1,2,3]:
for y in [1,2]:
if y in adict: # Check if we have y in adict or not
adict[y] += x
else: # If not, set it to x
adict[y] = x
print(adict)
Output:
>>> trial()
{1: 6, 2: 6}
Upvotes: 0
Reputation: 19634
You did not initialize adict
for each key. You can use defaultdict
to solve this issue:
from collections import defaultdict
def trial():
adict=defaultdict(int)
for x in [1,2,3]:
for y in [1,2]:
adict[y] += x
print(adict)
trial()
The result is defaultdict(<class 'int'>, {1: 6, 2: 6})
Upvotes: 1
Reputation: 977
You should modify youre code like this:
def trial():
adict={0,0,0}
for x in [1,2,3]:
for y in [1,2]:
adict[y] += x
print(adict)
"adict" has no entries. So adict[1] fails because it is accessing a variable that does not exist.
Upvotes: 0
Reputation: 599530
adict
starts off empty. You can't add an integer to a value that doesn't already exist.
Upvotes: 1