Mapping methods
>>> from collections import abc
>>> my_dict = {}
>>> isinstance(my_dict, abc.Mapping)
True
When an object considered hashbale?
In order an aobject to be hashable needs to have a hash value that never changes during its lifetime.
Implementation of:
-
__hash()__
```
{% endraw %}
-
{% raw %}
```python
__eq()__
```
{% endraw %}
are mandatory.
A tuple is hashable, if all items are hashable, example:
{% raw %}
```python
>>> tt = (1, 2, (30, 40))
>>> hash(tt)
8027212646858338501
>>> tl = (1, 2, [30, 40])
>>> hash(tl)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'list'
>>> tf = (1, 2, frozenset([30, 40]))
>>> hash(tf)
-4118419923444501110
dict comprehensions
>>> countries_codes = [('DK', 'Denmark'), ('GR', 'Greece'), ('IT', 'Italy')]
>>> codes_dict = {code: country_name for code, country_name in countries_codes}
>>> codes_dict
{'DK': 'Denmark', 'GR': 'Greece', 'IT': 'Italy'}
setdefault
my_dict.setdefault(key, []).append(new_value)
===
# …is the same as running…
if key not in my_dict:
my_dict[key] = []
my_dict[key].append(new_value)
default dict
>>> from collections import defaultdict
>>> my_dict = defaultdict(list)
>>> my_dict['a'].append(3)
>>> my_dict['a']
[3]
Immutable map
>>> from types import MappingProxyType
>>> d = {1: 'A'}
>>> d_proxy = MappingProxyType(d)
Set
# union
a | b
# intersection
a & b
# difference
a - b
Top comments (0)