Skip to content

dict vs defaultdict

Inspect the difference between a dict and a defaultdict in Python.

Access dict by key with square brackets

The easiest way to access a value inside dictionary is with [key] syntax. But be careful, if the key does not exist, you will get a KeyError.

src.beginner.dict_vs_defaultdict.get_value_from_dict_with_square_brackets(my_dict, key)

Get value from a dict using square brackets.

Parameters:

Name Type Description Default
my_dict dict[str, str]

dict to find value.

required
key str

key to find in the dict.

required

Returns:

Name Type Description
value str

value of the dict for the key provided.

Raises:

Type Description
KeyError

If key is not in the dict.

Source code in src/beginner/dict_vs_defaultdict/dict_vs_defaultdict.py
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
def get_value_from_dict_with_square_brackets(
    my_dict: dict[str, str],
    key: str,
) -> str:
    """Get value from a dict using square brackets.

    Parameters:
        my_dict (dict[str, str]): dict to find value.
        key (str): key to find in the dict.

    Returns:
        value (str): value of the dict for the key provided.

    Raises:
        KeyError: If key is not in the dict.
    """
    return my_dict[key]

Access dict by key with get method

Using get method is another option. If key is not present in dict, None (or custom value) is returned.

src.beginner.dict_vs_defaultdict.get_value_from_dict_with_get(my_dict, key, default=None)

Get value from a dict using get method.

Return default if key is not in the dict.

Parameters:

Name Type Description Default
my_dict dict[str, str]

dict to find value.

required
key str

key to find in the dict.

required
default str

default value to return if key is not in the dict.

None

Returns:

Name Type Description
value (str, None)

value of the dict for the key provided.

Source code in src/beginner/dict_vs_defaultdict/dict_vs_defaultdict.py
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
def get_value_from_dict_with_get(
    my_dict: dict[str, str],
    key: str,
    default: str = None,
) -> Optional[str]:
    """Get value from a dict using get method.

    Return default if key is not in the dict.

    Parameters:
        my_dict (dict[str, str]): dict to find value.
        key (str): key to find in the dict.
        default (str): default value to return if key is not in the
            dict.

    Returns:
        value (str, None): value of the dict for the key provided.
    """
    return my_dict.get(key, default)

Use defaultdict

defaultdict enables a dict with a default value, even if requested with square brackets. When setting defaultdict, you can send as first argument (default_factory) a function that will be called when key is not present in dict . String, int, list, None... any type you want. If you don't set default_factory, KeyError will be raised if key is not present.

src.beginner.dict_vs_defaultdict.get_value_from_defaultdict(my_dict, key, default=None)

Get value from a defaultdict using square brackets.

If a function is send as argument to defaultdict, it will use to return as the default value.

Parameters:

Name Type Description Default
my_dict dict[str, str]

defaultdict to find value.

required
key str

key to find in the defaultdict.

required
default str

default value class to return if key is not in the defaultdict.

None

Returns:

Name Type Description
value str

value of the defaultdict for the key provided.

Source code in src/beginner/dict_vs_defaultdict/dict_vs_defaultdict.py
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
def get_value_from_defaultdict(
    my_dict: dict[str, str],
    key: str,
    default: str = None,
) -> str:
    """Get value from a defaultdict using square brackets.

    If a function is send as argument to defaultdict,
    it will use to return as the default value.

    Parameters:
        my_dict (dict[str, str]): defaultdict to find value.
        key (str): key to find in the defaultdict.
        default (str): default value class to return if key is not in the
            defaultdict.

    Returns:
        value (str): value of the defaultdict for the key provided.
    """
    default_dict = defaultdict(lambda: default)
    default_dict.update(**my_dict)
    return default_dict[key]

Performance comparison

There is a great performance in using defaultdict vs get

from timeit import timeit

print("Get missing default dict:", timeit(
    stmt="default_dict.get('key')",
    setup="default_dict = {}",
    number=5000000)
)
Get missing default dict: 0.1267744980000316

print("Get missing collection default dict:", timeit(
    stmt="default_dict['key']",
    setup="from collections import defaultdict; default_dict = defaultdict(lambda: None)",  # noqa
    number=5000000)
)
Get missing collection default dict: 0.0706390929999543