Preferred Python idiom for handling non-existing dictionary keys and why?

Skip Montanaro skip at pobox.com
Fri Oct 10 15:33:53 EDT 2003


    >> Say I am populating a dictionary with a list and appending. I have
    >> written it thusly:

    John> You want the dict.setdefault method.

d.setdefault() never made any sense to me (IOW, to use it I always had to
look it up).  The semantics of what it does just never stick in my brain.
Consequently, even though it's less efficient I generally write such loops
like this:

    d = {}
    for (key, val) in some_items:
        lst = d.get(key) or []
        lst.append(val)
        d[key] = lst

Note that the first statement of the loop is correct (though perhaps not
obvious at first glance), since once initialized, d[key] never tests as
False.  FYI, timeit tells the performace tale:

    % timeit.py -s 'd={}' 'x = d.setdefault("x", [])'
    1000000 loops, best of 3: 1.82 usec per loop
    % timeit.py -s 'd={}' 'x = d.get("x") or [] ; d["x"] = x'
    100000 loops, best of 3: 2.34 usec per loop

But my way isn't bad enough for me to change. ;-)

Skip





More information about the Python-list mailing list