serhii.net

In the middle of the desert you can say anything you want

23 May 2022

python defaultdict

Using the Python defaultdict Type for Handling Missing Keys – Real Python

Python defaultdict is powerful, copying example from the excellent Real Python page above:

from collections import defaultdict, then things like:

>>> def_dict = defaultdict(list)  # Pass list to .default_factory
>>> def_dict['one'] = 1  # Add a key-value pair
>>> def_dict['missing']  # Access a missing key returns an empty list
[]
>>> def_dict['another_missing'].append(4)  # Modify a missing key

become possible.

God, how many times have I written ugly (or overkill-dataclasses) code for “if there’s a key in the dict, append to it, if not - create an empty list”

Nel mezzo del deserto posso dire tutto quello che voglio.
comments powered by Disqus