Tway101
Tway101

Reputation: 39

Python initialize empty dictionary with default values type

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

Answers (2)

Utsav Chokshi
Utsav Chokshi

Reputation: 1395

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

Upvotes: 0

Seleme
Seleme

Reputation: 251

Use defaultdict

from collections import defaultdict
mydict = defaultdict(set)
mydict["key"].add(5)

Upvotes: 3

Related Questions