Python: Snippet – Default dictionary

Normalerweise erzeugt ein Python Dictionary einen „KeyError“ wenn auf einen Key zugegriffen wird der nicht existiert. Mit „defaultdict“ werden die Keys einfach erzeugt wenn sie nicht existieren.

Ohne defaultdict:

>>> d = {}
>>> d['foobar']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'foobar'

Mit defaultdict:

>>> from collections import defaultdict
>>> d = defaultdict(dict)
>>> d['foobar']
{}
>>>

Das Verhalten hat natürlich Vorteile wenn man mehrdimensionale Dictionarys bauen will:

Ohne defaultdict:

>>> d = {}
>>> d['first'] = {}
>>> d['first']['second'] = "foobar"
>>> d
{'first': {'second': 'foobar'}}

Mit defaultdict:

>>> d = defaultdict(dict)
>>> d['first']['second'] = "foobar"
>>> d
defaultdict(<class 'dict'>, {'first': {'second': 'foobar'}})

Mehr dazu:

https://docs.python.org/3/library/collections.html

Schreibe einen Kommentar

Diese Website verwendet Akismet, um Spam zu reduzieren. Erfahre mehr darüber, wie deine Kommentardaten verarbeitet werden.