In the follwing code I wanted to use integers as keys in a dict:
import itertools N = {} for a,b,c,d in itertools.product(range(100), repeat=4): x = a*a + c*c y = a*b + c*d z = b*b + d*d s = x + y + y + z N[s] += 1 print N I get a KeyError: 0 at N[s] += 1. Why is it so? The documentation says that
strings and numbers can always be keys
The wiki gives an explanation on KeyError:
Python raises a KeyError whenever a dict() object is requested (using the format
a = adict[key]) and the key is not in the dictionary.
What I want to do is to build a dict with yet-unknown keys (they are computed on the fly) and keep a counter for them. I have done that in the past (with strings as keys) so what did I did wrong this time? (I know - this must be super obvious but after some time glaring at this complicated code I need help :))
Counter,from collections import Counter; N = Counter()