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?

2

2 Answers 2

3

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

Is it also possible to use just dict? i.e. mydict = dict(set)
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}}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.