How to make lists automatically instantiate on use in Python as they do in Perl? -
in perl, can this:
push(@{$h->[x]}, y);
can simplify following python codes according above perl example?
if x not in h: h[x] = [] h[x].append(y)
i want simplify this, because goes many places in code, (and cannot initialize possible x []). not want make function, because there no 'inline' keyword.
any ideas?
a elegant way (since python 2.5) use defaultdict
"collections" module:
>>> collections import defaultdict >>> h = defaultdict(list) >>> h['a'].append('b') >>> h defaultdict(<type 'list'>, {'a': ['b']})
defaultdict
dict, provides default value using whichever constructor passed when created (in example, list).
i particularly on setdefault
dict method, because 1) define variable defaultdict, , no other changes required on code (except perhaps remove previous kludges default values); , 2) setdefault terrible name :p
Comments
Post a Comment