I have a dictionary d of sets. When adding an element under some key key I consider the two cases key in d and not key in d:
from random import randint
for i in range(1000):
key = randint(0, 100)
if key in d:
d[key] |= set([randint(0, 10)])
else:
d[key] = set([randint(0, 10])
Is there a cleaner way to do this? Can I unify the two cases?
I like using a defaultdict, which is a kind of dictionary which creates a default object when you refer to a key which isn’t yet defined: