I saw someone use defaultdict(set)
to solve a problem after importing it from collections, but it was in passing so I didn't get to look at the problem fully. I know if you do defaultdict(int)
then every instance that is not already in a dictionary gets defaulted to 0. This can be useful because you don't have to use if/else statement when adding to the dictionary. However, what does passing set
through the parameter do? And what possible purpose can it serve, does it just mean only add the value to the dictionary if its not already there?
Asked
Active
Viewed 1,503 times
-1

jonrsharpe
- 115,751
- 26
- 228
- 437

PKPed
- 23
- 1
- 4
-
1Given that you know what `defaultdict(int)` does, it’s only a small step; every instance that’s not already in the dictionary (actually when you try to access a *key* that’s missing) gets defaulted to `set()` (an empty set) rather than `int()` (`0`, as you’ve already seen). – jonrsharpe Mar 18 '21 at 08:59
-
1Have you looked at the documentation for `defaultdict`? whatever you pass is used as a factory function for the default value. So `int() == 0`, and `set()` returns an empty set... – juanpa.arrivillaga Mar 18 '21 at 09:03
1 Answers
1
Example from the docs
>>> s = [('red', 1), ('blue', 2), ('red', 3), ('blue', 4), ('red', 1), ('blue', 4)]
>>> d = defaultdict(set)
>>> for k, v in s:
... d[k].add(v)
...
>>> sorted(d.items())
[('blue', {2, 4}), ('red', {1, 3})]
So if k
doesn't exist in the d
, it will add an empty set for this k
d[k] = set()
and add
d[k].add(v)

Tom Wojcik
- 5,471
- 4
- 32
- 44