DEV Community

Konstantinos Blatsoukas
Konstantinos Blatsoukas

Posted on

# Python dictionary

Mapping methods

>>> from collections import abc
>>> my_dict = {}
>>> isinstance(my_dict, abc.Mapping)
True
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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'}
Enter fullscreen mode Exit fullscreen mode

setdefault

my_dict.setdefault(key, []).append(new_value)
Enter fullscreen mode Exit fullscreen mode

===

# …is the same as running…
if key not in my_dict:
 my_dict[key] = []
my_dict[key].append(new_value)
Enter fullscreen mode Exit fullscreen mode

default dict

>>> from collections import defaultdict
>>> my_dict = defaultdict(list) 
>>> my_dict['a'].append(3) 
>>> my_dict['a'] 
[3]
Enter fullscreen mode Exit fullscreen mode

Immutable map

>>> from types import MappingProxyType
>>> d = {1: 'A'}
>>> d_proxy = MappingProxyType(d)
Enter fullscreen mode Exit fullscreen mode

Set

# union
a | b
# intersection
a & b
# difference
a - b
Enter fullscreen mode Exit fullscreen mode

Top comments (0)