Reputation: 39
I want to use a dictionary with string as key and set() as values.
How do I initialize an empty dictionary with a specific type as values?
I need it because I don't want to check everytime if the key is already in the dictionary and put an if to create the set instead of just using .add()
is it possible?
Upvotes: 1
Views: 6552
Reputation: 1395
You can also use setdefault()
function on standard python dict
to initialize keys not present.
setdefault() :
x=dict()
x.setdefault('a',set()).add(5)
print(x) #{'a': {5}}
x.setdefault('a',set()).add(6)
print(x) #{'a': {5, 6}}
Upvotes: 0
Reputation: 251
Use defaultdict
from collections import defaultdict
mydict = defaultdict(set)
mydict["key"].add(5)
Upvotes: 3