Quantcast
Viewing all articles
Browse latest Browse all 144

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


Viewing all articles
Browse latest Browse all 144