defaultdict(set)
时间: 2023-09-02 17:09:03 浏览: 68
python中defaultdict的用法详解
`defaultdict(set)` is a subclass of the built-in `defaultdict` class in Python that creates a dictionary where the default value is an empty set. This means that if a key is not present in the dictionary, it will automatically create a new key with an empty set as the value.
For example:
```python
from collections import defaultdict
d = defaultdict(set)
d['a'].add(1)
d['b'].add(2)
d['a'].add(3)
print(d) # defaultdict(<class 'set'>, {'a': {1, 3}, 'b': {2}})
```
In the above example, `d` is a `defaultdict` of sets. We add values to the dictionary using the `add()` method of the set. When we add the value `1` to the key `'a'`, it creates a new key `'a'` with an empty set as the value, and then adds `1` to that set. Similarly, it creates a new key `'b'` with an empty set as the value, and adds `2` to it. When we add the value `3` to the key `'a'`, it adds `3` to the existing set associated with the key `'a'`. Finally, we print the dictionary, which shows that it contains two keys, `'a'` and `'b'`, each associated with a set of values.
阅读全文