1

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?

Tway101
  • 39
  • 2
  • 5
  • 4
    You appear to be looking for [`defaultdict`](https://docs.python.org/3.8/library/collections.html#collections.defaultdictt) – David Buck Mar 23 '20 at 18:41
  • Does this answer your question? [Dictionaries and default values](https://stackoverflow.com/questions/9358983/dictionaries-and-default-values) – AMC Mar 23 '20 at 21:39

2 Answers2

3

Use defaultdict

from collections import defaultdict
mydict = defaultdict(set)
mydict["key"].add(5)
Seleme
  • 241
  • 1
  • 8
0

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}}

Utsav Chokshi
  • 1,357
  • 1
  • 13
  • 35