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?
2 Answers 2
Use defaultdict
from collections import defaultdict
mydict = defaultdict(set)
mydict["key"].add(5)
Sign up to request clarification or add additional context in comments.
1 Comment
Egret
Is it also possible to use just
dict? i.e. mydict = dict(set)You can also use setdefault() function on standard python dict to initialize keys not present.
setdefault() :
- returns default value passed if key is not present.
- returns None if key is not present and no default value passed
- returns value of key if key is present.
x=dict()
x.setdefault('a',set()).add(5)
print(x) #{'a': {5}}
x.setdefault('a',set()).add(6)
print(x) #{'a': {5, 6}}
answered Mar 23, 2020 at 19:59
Utsav Chokshi
1,4051 gold badge15 silver badges37 bronze badges
Comments
lang-py
defaultdict