Developpez.com

Python

Choisissez la catégorie, puis la rubrique :

5.3.2 defaultdict objects


5.3.2 defaultdict objects

defaultdict( [default_factory[, ...]])
Returns a new dictionary-like object. defaultdict is a subclass of the builtin dict class. It overrides one method and adds one writable instance variable. The remaining functionality is the same as for the dict class and is not documented here.

The first argument provides the initial value for the default_factory attribute; it defaults to None. All remaining arguments are treated the same as if they were passed to the dict constructor, including keyword arguments.

New in version 2.5.

defaultdict objects support the following method in addition to the standard dict operations:

__missing__( key)
If the default_factory attribute is None, this raises an KeyError exception with the key as argument.

If default_factory is not None, it is called without arguments to provide a default value for the given key, this value is inserted in the dictionary for the key, and returned.

If calling default_factory raises an exception this exception is propagated unchanged.

This method is called by the __getitem__ method of the dict class when the requested key is not found; whatever it returns or raises is then returned or raised by __getitem__.

defaultdict objects support the following instance variable:

default_factory
This attribute is used by the __missing__ method; it is initialized from the first argument to the constructor, if present, or to None, if absent.



See About this document... for information on suggesting changes.
Microsoft publie l'édition de juin 2019 de l'extension Python pour Visual Studio Code, elle inclut 70 correctifs et son lot de nouveautés
Le neuvième week-end de programmation de jeux vidéo sur Developpez.com
Programmation : une étude révèle les langages les plus voraces en énergie, Perl, Python et Ruby en tête, C, Rust et C++, les langages les plus verts
Apprendre les notions avancées en Cython, un tutoriel de Gabor Laszlo Hajba traduit par l'équipe de rédaction
Contacter le responsable de la rubrique Python

Partenaire : Hébergement Web