python-How to solve KeyError: 2?

In order to set a general default value for all keys, you can use defaultdict:

from collections import defaultdict

d = defaultdict(list)    
d[0].append(1)

Leave a Comment