Auto-vivification in Python 3.x


Are you spoiled by Perl’s auto-vivification allowing to write such code and you want to do the same in Python ?

 yourdict[yourkey][newkey1][newkey2] = 42;

An often used, somewhat ugly code pattern where you need to add a key in a dict when it’s not there yet:

yourdict = {}
for item in items:
    ...
    if yourkey not in yourdict:
        yourdict[yourkey] = ()
   yourdict[yourkey].append(item)

There is a better way since Python 3.3 (even if Perl’s type of deep-structure on-the-fly creation is not there) :

from collections import defaultdict
yourdict = defaultdict(list)
for item in items:
    ...
   yourdict[yourkey].append(item)

oh, and you are running Python 3.x everywhere, correct ? Python 2.x is obsolete / end-of-life since 1.1.2020. Talk to us if you still run Python 2.x code and need help to port it to Python 3.x.